From a23faf2f9d41247edae9e7acbaf55dac8216189d Mon Sep 17 00:00:00 2001 From: Akshay Pal Date: Sat, 24 Oct 2026 23:44:43 +0100 Subject: [PATCH] chore: prepare Basis for personal OSS development --- .clang-format | 24 +- .editorconfig | 15 + .github/ISSUE_TEMPLATE/bug.md | 13 + .github/ISSUE_TEMPLATE/defect.md | 20 - .github/ISSUE_TEMPLATE/feature.md | 19 +- .github/pull_request_template.md | 11 + .github/workflows/ci.yml | 39 + .github/workflows/manual-packager.yaml | 309 - .github/workflows/pr-checks.yaml | 93 - .github/workflows/release-please.yaml | 23 - .gitignore | 52 +- .release-please-manifest.json | 3 - CHANGELOG.md | 29 +- CITATION.cff | 5 +- CMakeLists.txt | 112 +- CMakePresets.json | 82 + CODE_OF_CONDUCT.md | 100 +- CONTRIBUTING.md | 63 +- README.md | 116 +- SECURITY.md | 12 + docs/README.md | 45 +- docs/architecture.md | 15 + docs/builtins-and-gates.md | 2 +- docs/casting.md | 2 +- docs/classes-and-objects.md | 2 +- docs/control-flow.md | 4 +- docs/cpp-style.md | 396 + docs/diagnostics.md | 2 +- docs/examples.md | 14 +- docs/functions-and-modules.md | 2 +- docs/getting-started.md | 125 +- docs/grammar.md | 2 +- docs/known-issues.md | 12 + docs/language-spec.md | 8 +- docs/language-tour.md | 4 +- docs/overview.md | 29 +- docs/quantum-programming.md | 4 +- docs/runtime.md | 4 +- docs/tooling-and-cli.md | 63 +- docs/troubleshooting.md | 6 +- docs/types-and-data.md | 2 +- engineering/adrs/ADR-001-class-system.md | 60 - engineering/adrs/ADR-002-null-handling.md | 29 - engineering/adrs/ADR-003-generics.md | 50 - engineering/adrs/ADR-004-shots-annotation.md | 28 - .../adrs/ADR-005-new-v1.1.0-primitives.md | 30 - engineering/adrs/ADR-006-stdlib-boxing.md | 45 - .../adrs/ADR-007-stdlib-collections.md | 39 - engineering/adrs/ADR-008-custom-http-lib.md | 31 - engineering/adrs/ADR-009-import-system.md | 123 - .../adrs/ADR-010-lattice-build-system.md | 109 - engineering/designs/DES-001-class-system.md | 176 - engineering/designs/DES-002-shots.md | 28 - engineering/designs/DES-003-primitives.md | 33 - engineering/designs/DES-004-boxing.md | 106 - .../designs/DES-005-stdlib-collections.md | 63 - .../designs/DES-006-custom-http-lib.md | 32 - engineering/designs/DES-007-import-system.md | 145 - .../designs/DES-008-lattice-build-system.md | 93 - engineering/reference/README.md | 29 - engineering/reference/architecture.md | 18 - engineering/reference/ast.md | 28 - engineering/reference/builtins.md | 25 - engineering/reference/cli.md | 42 - engineering/reference/codebase-overview.md | 36 - engineering/reference/coding-standards.md | 35 - engineering/reference/how-to-contribute.md | 46 - engineering/reference/lexer.md | 36 - engineering/reference/module-loader.md | 38 - engineering/reference/parser.md | 36 - engineering/reference/qasm-mapping.md | 73 - engineering/reference/qasm-simulator.md | 33 - engineering/reference/runtime-evaluator.md | 36 - engineering/reference/semantics.md | 44 - engineering/reference/support-and-errors.md | 29 - engineering/reference/testing.md | 24 - engineering/reference/update-manager.md | 34 - examples/README.md | 38 +- examples/multifile/main.qasm | 4 - justfile | 33 + paper/paper.md | 4 +- release-please-config.json | 16 - scripts/build_and_test.sh | 110 - scripts/check-install.sh | 36 + scripts/format.sh | 65 +- scripts/install.ps1 | 121 - scripts/install.sh | 335 +- scripts/run_examples.sh | 6 +- src/CMakeLists.txt | 165 +- src/bloch/cli/cli.cpp | 640 +- src/bloch/cli/cli.hpp | 12 +- src/bloch/compiler/ast/ast.hpp | 1247 +- src/bloch/compiler/import/module_loader.cpp | 506 +- src/bloch/compiler/import/module_loader.hpp | 58 +- src/bloch/compiler/lexer/lexer.cpp | 579 +- src/bloch/compiler/lexer/lexer.hpp | 75 +- src/bloch/compiler/lexer/token.hpp | 214 +- src/bloch/compiler/parser/parser.cpp | 3009 ++-- src/bloch/compiler/parser/parser.hpp | 234 +- src/bloch/compiler/semantics/built_ins.cpp | 22 +- src/bloch/compiler/semantics/built_ins.hpp | 17 +- .../compiler/semantics/semantic_analyser.cpp | 5301 ++++--- .../compiler/semantics/semantic_analyser.hpp | 414 +- src/bloch/compiler/semantics/type_system.cpp | 220 +- src/bloch/compiler/semantics/type_system.hpp | 80 +- src/bloch/http/http_client.cpp | 44 - src/bloch/http/http_client.hpp | 51 - src/bloch/runtime/qasm_simulator.cpp | 420 +- src/bloch/runtime/qasm_simulator.hpp | 63 +- src/bloch/runtime/runtime_evaluator.cpp | 5834 ++++---- src/bloch/runtime/runtime_evaluator.hpp | 605 +- src/bloch/support/error/bloch_error.hpp | 164 +- src/bloch/update/update_manager.cpp | 780 - src/bloch/update/update_manager.hpp | 26 - src/main.cpp | 2 +- src/third_party/cpp-httplib/LICENSE | 22 - src/third_party/cpp-httplib/httplib.h | 12380 ---------------- tests/CMakeLists.txt | 41 +- tests/test_ast.cpp | 2 +- tests/test_framework.hpp | 198 +- tests/test_integration.cpp | 264 +- tests/test_lexer.cpp | 2 +- tests/test_main.cpp | 2 +- tests/test_parser.cpp | 2 +- tests/test_runtime.cpp | 5 +- tests/test_semantics.cpp | 2 +- version.txt | 1 + 127 files changed, 11216 insertions(+), 27000 deletions(-) create mode 100644 .editorconfig create mode 100644 .github/ISSUE_TEMPLATE/bug.md delete mode 100644 .github/ISSUE_TEMPLATE/defect.md create mode 100644 .github/pull_request_template.md create mode 100644 .github/workflows/ci.yml delete mode 100644 .github/workflows/manual-packager.yaml delete mode 100644 .github/workflows/pr-checks.yaml delete mode 100644 .github/workflows/release-please.yaml delete mode 100644 .release-please-manifest.json create mode 100644 CMakePresets.json create mode 100644 SECURITY.md create mode 100644 docs/architecture.md create mode 100644 docs/cpp-style.md create mode 100644 docs/known-issues.md delete mode 100644 engineering/adrs/ADR-001-class-system.md delete mode 100644 engineering/adrs/ADR-002-null-handling.md delete mode 100644 engineering/adrs/ADR-003-generics.md delete mode 100644 engineering/adrs/ADR-004-shots-annotation.md delete mode 100644 engineering/adrs/ADR-005-new-v1.1.0-primitives.md delete mode 100644 engineering/adrs/ADR-006-stdlib-boxing.md delete mode 100644 engineering/adrs/ADR-007-stdlib-collections.md delete mode 100644 engineering/adrs/ADR-008-custom-http-lib.md delete mode 100644 engineering/adrs/ADR-009-import-system.md delete mode 100644 engineering/adrs/ADR-010-lattice-build-system.md delete mode 100644 engineering/designs/DES-001-class-system.md delete mode 100644 engineering/designs/DES-002-shots.md delete mode 100644 engineering/designs/DES-003-primitives.md delete mode 100644 engineering/designs/DES-004-boxing.md delete mode 100644 engineering/designs/DES-005-stdlib-collections.md delete mode 100644 engineering/designs/DES-006-custom-http-lib.md delete mode 100644 engineering/designs/DES-007-import-system.md delete mode 100644 engineering/designs/DES-008-lattice-build-system.md delete mode 100644 engineering/reference/README.md delete mode 100644 engineering/reference/architecture.md delete mode 100644 engineering/reference/ast.md delete mode 100644 engineering/reference/builtins.md delete mode 100644 engineering/reference/cli.md delete mode 100644 engineering/reference/codebase-overview.md delete mode 100644 engineering/reference/coding-standards.md delete mode 100644 engineering/reference/how-to-contribute.md delete mode 100644 engineering/reference/lexer.md delete mode 100644 engineering/reference/module-loader.md delete mode 100644 engineering/reference/parser.md delete mode 100644 engineering/reference/qasm-mapping.md delete mode 100644 engineering/reference/qasm-simulator.md delete mode 100644 engineering/reference/runtime-evaluator.md delete mode 100644 engineering/reference/semantics.md delete mode 100644 engineering/reference/support-and-errors.md delete mode 100644 engineering/reference/testing.md delete mode 100644 engineering/reference/update-manager.md delete mode 100644 examples/multifile/main.qasm create mode 100644 justfile delete mode 100644 release-please-config.json delete mode 100755 scripts/build_and_test.sh create mode 100755 scripts/check-install.sh delete mode 100644 scripts/install.ps1 mode change 100644 => 100755 scripts/install.sh delete mode 100644 src/bloch/http/http_client.cpp delete mode 100644 src/bloch/http/http_client.hpp delete mode 100644 src/bloch/update/update_manager.cpp delete mode 100644 src/bloch/update/update_manager.hpp delete mode 100644 src/third_party/cpp-httplib/LICENSE delete mode 100644 src/third_party/cpp-httplib/httplib.h create mode 100644 version.txt diff --git a/.clang-format b/.clang-format index cad9139..e5041e8 100644 --- a/.clang-format +++ b/.clang-format @@ -1,23 +1,21 @@ -# Style base BasedOnStyle: Google +Language: Cpp +Standard: c++20 -# Style IndentWidth: 4 TabWidth: 4 UseTab: Never + ColumnLimit: 100 -BreakBeforeBraces: Attach -SpaceBeforeParens: ControlStatements + +NamespaceIndentation: None +FixNamespaceComments: true + DerivePointerAlignment: false PointerAlignment: Left -SortIncludes: true -IncludeBlocks: Preserve -AllowShortIfStatementsOnASingleLine: false -NamespaceIndentation: All -FixNamespaceComments: false -# C++ specific -Language: Cpp +SortIncludes: true +IncludeBlocks: Regroup -# Quoting style -AlwaysBreakTemplateDeclarations: Yes \ No newline at end of file +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false \ No newline at end of file diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..c90b128 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 + +[*.{yml,yaml,json}] +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md new file mode 100644 index 0000000..598a9c2 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.md @@ -0,0 +1,13 @@ +--- +name: Bug report +about: Report a reproducible problem +--- + +**Basis version or commit:** +**Operating system and compiler:** + +**Minimal program and command:** + +**Expected result:** + +**Actual result and full diagnostic:** diff --git a/.github/ISSUE_TEMPLATE/defect.md b/.github/ISSUE_TEMPLATE/defect.md deleted file mode 100644 index f248543..0000000 --- a/.github/ISSUE_TEMPLATE/defect.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -name: Defect -about: Create a report to help us improve -title: '' -labels: 'bug' -assignees: '' - ---- - -**Problem Overview** -A clear and concise description of what the bug is. - -**Impact** -How does this impact behaviour? - -**Steps to Recreate** -Steps required to recreate the defect locally. - -**Fix Ideas** -Any ideas on what to change? \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature.md b/.github/ISSUE_TEMPLATE/feature.md index 71439f1..8bdc98c 100644 --- a/.github/ISSUE_TEMPLATE/feature.md +++ b/.github/ISSUE_TEMPLATE/feature.md @@ -1,17 +1,12 @@ --- -name: Feature -about: Propose a new feature -title: '' -labels: 'feature' -assignees: '' - +name: Feature proposal +about: Propose a focused improvement --- -**Problem Overview** -A clear and concise description of the feature. +**Problem or use case:** + +**Proposed behaviour:** -**Work Required** -How will this be implemented (leave blank if unsure). +**Example program or command:** -**Acceptance Criteria** -What defines acceptance for this feature? \ No newline at end of file +**Alternatives considered:** diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..149488f --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,11 @@ +## What changed? + +Describe the problem and resulting behaviour. + +## Validation + +Describe the relevant checks and tests. Run `just check` before requesting review. + +## Related issue + +Link the issue if applicable. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c819aa7 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,39 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + check: + name: Check (${{ matrix.compiler }}) + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + include: + - compiler: gcc + cxx: g++ + - compiler: clang + cxx: clang++-18 + env: + CXX: ${{ matrix.cxx }} + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - name: Install tools + run: | + sudo apt-get update + sudo apt-get install --yes cmake ninja-build g++ clang-18 clang-format-18 just + - run: just check diff --git a/.github/workflows/manual-packager.yaml b/.github/workflows/manual-packager.yaml deleted file mode 100644 index 3ee55b6..0000000 --- a/.github/workflows/manual-packager.yaml +++ /dev/null @@ -1,309 +0,0 @@ -name: Manual Packager - -on: - workflow_dispatch: - inputs: - tag: - description: Release tag to package (must exist on main) - required: true - -permissions: - contents: write - -env: - BLOCH_VERSION: ${{ inputs.tag }} - -jobs: - ff-main: - name: Fast-forward main to tag - runs-on: ubuntu-latest - steps: - - name: Checkout main - uses: actions/checkout@v4 - with: - ref: main - fetch-depth: 0 - - - name: Ensure tag exists and fast-forward main - env: - TAG: ${{ inputs.tag }} - run: | - set -euo pipefail - git fetch origin main develop --tags - - if ! git rev-parse "refs/tags/$TAG" >/dev/null 2>&1; then - echo "Tag $TAG not found." >&2 - exit 1 - fi - - if git merge-base --is-ancestor "refs/tags/$TAG" origin/main; then - echo "Tag $TAG is already reachable from origin/main." - exit 0 - fi - - if git merge-base --is-ancestor "refs/tags/$TAG" origin/develop; then - echo "Fast-forwarding main to $TAG" - git checkout main - git merge --ff-only "refs/tags/$TAG" - git push origin main - exit 0 - fi - - echo "Tag $TAG is not reachable from origin/main or origin/develop." >&2 - exit 1 - - package: - needs: ff-main - env: - VCPKG_ROOT: ${{ github.workspace }}/.vcpkg - VCPKG_FORCE_SYSTEM_BINARIES: 1 - VCPKG_DOWNLOADS: ${{ github.workspace }}/.vcpkg_downloads - VCPKG_DEFAULT_BINARY_CACHE: ${{ github.workspace }}/.vcpkg_cache - strategy: - matrix: - include: - - runner: ubuntu-latest - os_name: Linux - arch: X64 - cpack_generator: TGZ - artifact_ext: tar.gz - - runner: macos-15-intel - os_name: macOS - arch: X64 - cpack_generator: TGZ - artifact_ext: tar.gz - - runner: macos-latest - os_name: macOS - arch: ARM64 - cpack_generator: TGZ - artifact_ext: tar.gz - - runner: windows-latest - os_name: Windows - arch: X64 - cpack_generator: ZIP - artifact_ext: zip - runs-on: ${{ matrix.runner }} - - steps: - - name: Checkout release tag - uses: actions/checkout@v4 - with: - ref: refs/tags/${{ inputs.tag }} - fetch-depth: 0 - fetch-tags: true - - - name: Verify tag is on main - shell: bash - run: | - set -euo pipefail - git fetch origin main --tags --force --prune - if ! git merge-base --is-ancestor "refs/tags/${{ inputs.tag }}" origin/main; then - echo "Tag ${{ inputs.tag }} is not reachable from origin/main." >&2 - exit 1 - fi - - - name: Restore vcpkg caches (Windows) - if: matrix.runner == 'windows-latest' - uses: actions/cache@v4 - with: - path: | - .vcpkg_cache - .vcpkg_downloads - key: vcpkg-${{ runner.os }}-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json') }} - restore-keys: | - vcpkg-${{ runner.os }}- - - - name: Ensure vcpkg cache dirs (Windows) - if: matrix.runner == 'windows-latest' - shell: pwsh - run: | - New-Item -ItemType Directory -Force -Path "$env:VCPKG_DOWNLOADS" | Out-Null - New-Item -ItemType Directory -Force -Path "$env:VCPKG_DEFAULT_BINARY_CACHE" | Out-Null - - - name: Ensure CMake 3.31.10 (Windows) - if: matrix.runner == 'windows-latest' - shell: pwsh - run: | - $ver = "3.31.10" - $zip = "$env:RUNNER_TEMP\cmake-$ver.zip" - Invoke-WebRequest -Uri "https://cmake.org/files/v3.31/cmake-$ver-windows-x86_64.zip" -OutFile $zip - Expand-Archive $zip -DestinationPath "$env:RUNNER_TEMP\cmake" - $cmakeDir = Get-ChildItem "$env:RUNNER_TEMP\cmake" -Directory | Select-Object -First 1 - "$($cmakeDir.FullName)\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append - - - name: Install build deps (Linux) - if: matrix.runner == 'ubuntu-latest' - run: | - sudo apt-get update - sudo apt-get install -y cmake g++ libssl-dev pkg-config - - - name: Install build deps (macOS) - if: startsWith(matrix.runner, 'macos-') - run: | - brew update - brew install openssl@3 - - - name: Install vcpkg (Windows) - if: matrix.runner == 'windows-latest' - shell: pwsh - run: | - git clone https://github.com/microsoft/vcpkg $env:VCPKG_ROOT - & "$env:VCPKG_ROOT\bootstrap-vcpkg.bat" -disableMetrics - - - name: Pre-fetch Ninja (Windows) - if: matrix.runner == 'windows-latest' - shell: pwsh - run: | - $destDir = "$env:VCPKG_DOWNLOADS" - New-Item -ItemType Directory -Force -Path $destDir | Out-Null - $target = Join-Path $destDir "ninja-win-1.13.1.zip" - if (!(Test-Path $target)) { - $url = "https://github.com/ninja-build/ninja/releases/download/v1.13.1/ninja-win.zip" - for ($i = 0; $i -lt 3; $i++) { - Write-Host "Attempting ninja download ($($i+1))/3" - try { - Invoke-WebRequest -Uri $url -OutFile $target -UseBasicParsing -MaximumRedirection 5 - break - } catch { - Write-Warning "Download attempt $($i+1) failed: $_" - Start-Sleep -Seconds 5 - } - } - if (!(Test-Path $target)) { - Write-Error "Failed to prefetch ninja" - exit 1 - } - } - - - name: Pre-fetch OpenSSL source (Windows) - if: matrix.runner == 'windows-latest' - shell: pwsh - run: | - $destDir = "$env:VCPKG_DOWNLOADS" - New-Item -ItemType Directory -Force -Path $destDir | Out-Null - $target = Join-Path $destDir "openssl-openssl-openssl-3.6.0.tar.gz" - if (!(Test-Path $target)) { - $urls = @( - "https://www.openssl.org/source/openssl-3.6.0.tar.gz", - "https://www.openssl.org/source/old/3.6/openssl-3.6.0.tar.gz" - ) - foreach ($u in $urls) { - Write-Host "Attempting download from $u" - try { - Invoke-WebRequest -Uri $u -OutFile $target -UseBasicParsing -MaximumRedirection 5 - break - } catch { - Write-Warning "Download failed from $u : $_" - } - } - if (!(Test-Path $target)) { - Write-Error "Failed to prefetch OpenSSL source" - exit 1 - } - } - - - name: Install OpenSSL (Windows) - if: matrix.runner == 'windows-latest' - shell: pwsh - run: | - & "$env:VCPKG_ROOT\vcpkg.exe" install openssl:x64-windows-static - - - name: Configure - shell: bash - run: | - if [[ "${{ matrix.runner }}" == "windows-latest" ]]; then - cmake -S . -B build -G "Visual Studio 17 2022" -A x64 -DCMAKE_BUILD_TYPE=Release \ - -DCMAKE_TOOLCHAIN_FILE="${VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake" \ - -DVCPKG_TARGET_TRIPLET=x64-windows-static \ - -DOPENSSL_USE_STATIC_LIBS=ON - elif [[ "${{ matrix.runner }}" == macos-* ]]; then - OPENSSL_ROOT=$(brew --prefix openssl@3) - cmake -S . -B build -DCMAKE_BUILD_TYPE=Release \ - -DOPENSSL_ROOT_DIR="${OPENSSL_ROOT}" \ - -DOPENSSL_USE_STATIC_LIBS=ON - else - cmake -S . -B build -DCMAKE_BUILD_TYPE=Release \ - -DOPENSSL_USE_STATIC_LIBS=ON - fi - - - name: Build - shell: bash - run: | - if [[ "${{ matrix.runner }}" == "windows-latest" ]]; then - cmake --build build --config Release - else - cmake --build build --parallel - fi - - - name: Run tests - shell: bash - run: | - if [[ "${{ matrix.runner }}" == "windows-latest" ]]; then - ctest --test-dir build -C Release --output-on-failure - else - ctest --test-dir build --output-on-failure - fi - - - name: Package - shell: bash - run: | - cpack -G "${{ matrix.cpack_generator }}" -B dist --config build/CPackConfig.cmake - shopt -s nullglob - files=(dist/*.${{ matrix.artifact_ext }}) - if [[ ${#files[@]} -ne 1 ]]; then - echo "Expected exactly one package, found ${#files[@]}." >&2 - exit 1 - fi - dest="dist/bloch-${{ inputs.tag }}-${{ matrix.os_name }}-${{ matrix.arch }}.${{ matrix.artifact_ext }}" - mv "${files[0]}" "$dest" - if command -v python3 >/dev/null 2>&1; then - PYTHON_BIN=python3 - elif command -v python >/dev/null 2>&1; then - PYTHON_BIN=python - else - echo "Python is required to compute checksums" >&2 - exit 1 - fi - PKG_PATH="$dest" "$PYTHON_BIN" - <<'PY' > "dist/checksums-${{ matrix.os_name }}-${{ matrix.arch }}.txt" - import hashlib, pathlib, os - path = pathlib.Path(os.environ["PKG_PATH"]) - digest = hashlib.sha256(path.read_bytes()).hexdigest() - print(f"{digest} {path.name}") - PY - ls -l dist - - - name: Upload artifacts - uses: actions/upload-artifact@v4 - with: - name: bloch-${{ inputs.tag }}-${{ matrix.os_name }}-${{ matrix.arch }} - path: | - dist/bloch-${{ inputs.tag }}-${{ matrix.os_name }}-${{ matrix.arch }}.${{ matrix.artifact_ext }} - dist/checksums-${{ matrix.os_name }}-${{ matrix.arch }}.txt - - release: - runs-on: ubuntu-latest - needs: package - steps: - - name: Download packaged artifacts - uses: actions/download-artifact@v4 - with: - pattern: bloch-${{ inputs.tag }}-* - path: dist - - - name: Build global checksums.txt - shell: bash - run: | - set -euo pipefail - find dist -name 'checksums-*.txt' -type f -print -exec cat {} \; > dist/checksums.txt - ls -l dist/checksums.txt - - - name: Create GitHub release - uses: softprops/action-gh-release@v1 - with: - tag_name: ${{ inputs.tag }} - name: Bloch ${{ inputs.tag }} - draft: false - prerelease: ${{ contains(inputs.tag, 'rc') }} - files: dist/** - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/pr-checks.yaml b/.github/workflows/pr-checks.yaml deleted file mode 100644 index 379aaf7..0000000 --- a/.github/workflows/pr-checks.yaml +++ /dev/null @@ -1,93 +0,0 @@ -name: PR Checks - -on: - pull_request: - branches: - - develop - - main - -permissions: - contents: read - pull-requests: read - statuses: write - -concurrency: - group: pr-${{ github.event.pull_request.head.ref || github.ref }} - cancel-in-progress: true - -jobs: - semantic: - name: Check PR Title - runs-on: ubuntu-latest - steps: - - uses: amannn/action-semantic-pull-request@v5 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - types: | - feat - fix - perf - refactor - revert - docs - test - build - ci - chore - requireScope: false - wip: true - - build: - name: Build & Test - runs-on: ubuntu-latest - needs: semantic - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Install Dependencies - run: | - sudo apt-get update - sudo apt-get install -y cmake g++ clang-format-14 - - name: Check Formatting - env: - CLANG_FORMAT: clang-format-14 - run: | - set -euo pipefail - mapfile -t files < <(find src tests -type f \( -name '*.c' -o -name '*.cpp' -o -name '*.h' -o -name '*.hpp' \)) - if [ "${#files[@]}" -gt 0 ]; then - printf '%s\0' "${files[@]}" | xargs -0 "$CLANG_FORMAT" -style=file --dry-run --Werror - fi - - name: Configure CMake (Release) - run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release - - name: Build - run: cmake --build build --parallel - - name: Run unit and integration tests - run: ctest --test-dir build --output-on-failure - - name: Run acceptance tests - run: bash scripts/run_examples.sh build/bin/bloch - - debug-build: - name: Debug Build Check for Release - if: startsWith(github.head_ref, 'release-please-') - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Install dependencies - run: | - sudo apt-get update - sudo apt-get install -y cmake g++ libssl-dev pkg-config - - - name: Configure CMake (Debug) - run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug - - - name: Build - run: cmake --build build --parallel - - - name: Run unit and integration tests - run: ctest --test-dir build --output-on-failure - - - name: Run acceptance tests - run: bash scripts/run_examples.sh build/bin/bloch diff --git a/.github/workflows/release-please.yaml b/.github/workflows/release-please.yaml deleted file mode 100644 index 4b3e02c..0000000 --- a/.github/workflows/release-please.yaml +++ /dev/null @@ -1,23 +0,0 @@ -name: release-please -on: - push: - branches: - - develop - - main - workflow_dispatch: - -permissions: - contents: write - pull-requests: write - -jobs: - release-please: - runs-on: ubuntu-latest - steps: - - name: Create or update release PR / tag - uses: googleapis/release-please-action@v4 - with: - token: ${{ secrets.GITHUB_TOKEN }} - config-file: release-please-config.json - manifest-file: .release-please-manifest.json - target-branch: ${{ github.ref_name }} diff --git a/.gitignore b/.gitignore index 8481cd7..810baeb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,41 +1,15 @@ -# CMake build folders -/build -/build-debug -/build-release -/CMakeFiles -/CMakeCache.txt -Makefile -cmake_install.cmake - -# VSCode -.vscode/ - -# Binaries -*.exe -*.out -*.app -*.dll -*.so -*.dylib - -# Object files +/build/ +/dist/ +/CMakeUserPresets.json +/compile_commands.json +/.cache/ +/.vscode/ +/.idea/ +.DS_Store *.o *.obj - -# Clangd index -.cache/ - -# Generated files -compile_commands.json -dist/ - -# Packages (optional local builds) -*.deb -*.rpm - -# Examples folder -examples/*.qasm - -# JOSS -paper/jats/ -paper/paper.pdf +*.exe +*.out +*.qasm +/paper/paper.pdf +/paper/jats/ diff --git a/.release-please-manifest.json b/.release-please-manifest.json deleted file mode 100644 index 122a59d..0000000 --- a/.release-please-manifest.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - ".": "1.0.4" -} diff --git a/CHANGELOG.md b/CHANGELOG.md index 2bb0afe..9916c16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,23 +1,28 @@ # Changelog -## [1.0.4](https://github.com/bloch-labs/bloch/compare/v1.0.3...v1.0.4) (2026-02-21) +## Unreleased — Basis v2 development + +- Resume development in the original repository under the Basis name. +- Add a personal OSS contribution workflow, just commands and tested source installation. + +## [1.0.4](https://github.com/akshaysoftware/basis/compare/v1.0.3...v1.0.4) (2026-02-21) ### Bug Fixes -* reset analyser state and make scope unwinding exception-safe ([#239](https://github.com/bloch-labs/bloch/issues/239)) ([df13d7a](https://github.com/bloch-labs/bloch/commit/df13d7a7e22ce2aaa89188e5a3f0a44b8f8e3fdb)) +* reset analyser state and make scope unwinding exception-safe ([#239](https://github.com/akshaysoftware/basis/issues/239)) ([df13d7a](https://github.com/akshaysoftware/basis/commit/df13d7a7e22ce2aaa89188e5a3f0a44b8f8e3fdb)) -## [1.0.2](https://github.com/bloch-labs/bloch/compare/v1.0.1...v1.0.2) (2025-12-11) +## [1.0.2](https://github.com/akshaysoftware/basis/compare/v1.0.1...v1.0.2) (2025-12-11) ### Bug Fixes -* hotfix windows build ([#189](https://github.com/bloch-labs/bloch/issues/189)) ([148bb3d](https://github.com/bloch-labs/bloch/commit/148bb3d30ea48dd48a7a80047cc9c69e580ffe25)) -* cx gate works on subspace where ctrl is 1 only ([#180](https://github.com/bloch-labs/bloch/issues/180)) ([6938c5d](https://github.com/bloch-labs/bloch/commit/6938c5db489ddf2f044d62855355f335059635de)) -* fixed bug where arrays could only be initialised by literals ([#185](https://github.com/bloch-labs/bloch/issues/185)) ([4c676f3](https://github.com/bloch-labs/bloch/commit/4c676f3e60bec386cc99f1bbefbbc0cab71c59f3)) -* initialise m_state to a single amplitude ([#177](https://github.com/bloch-labs/bloch/issues/177)) ([b6d59e2](https://github.com/bloch-labs/bloch/commit/b6d59e232394be9583aaa4366cf96ba4eea5d4d1)) -* install scripts migrated to website, added update checker ([#184](https://github.com/bloch-labs/bloch/issues/184)) ([fee4115](https://github.com/bloch-labs/bloch/commit/fee411539b8778d3cc3550d7df23de1f4d725514)) -* optimise qasm logging for better performance ([#178](https://github.com/bloch-labs/bloch/issues/178)) ([a2b9cd4](https://github.com/bloch-labs/bloch/commit/a2b9cd4eb7c56efa215b3cf50675ad8278d618de)) -* parenthesised expressions not being evaluated at runtime ([#182](https://github.com/bloch-labs/bloch/issues/182)) ([68c6371](https://github.com/bloch-labs/bloch/commit/68c63719bc430da35315b4bffc9b5472298b2beb)) -* **perf:** made runtime evaluator single use to prevent state leakage ([#170](https://github.com/bloch-labs/bloch/issues/170)) ([87afa42](https://github.com/bloch-labs/bloch/commit/87afa428208e60bcada4ab4183399ad94ed4e88d)) -* reset now clears measured flag ([#172](https://github.com/bloch-labs/bloch/issues/172)) ([e07f9fd](https://github.com/bloch-labs/bloch/commit/e07f9fdd76c9a20e89ccd025aef92e6ae45e4e9f)) \ No newline at end of file +* hotfix windows build ([#189](https://github.com/akshaysoftware/basis/issues/189)) ([148bb3d](https://github.com/akshaysoftware/basis/commit/148bb3d30ea48dd48a7a80047cc9c69e580ffe25)) +* cx gate works on subspace where ctrl is 1 only ([#180](https://github.com/akshaysoftware/basis/issues/180)) ([6938c5d](https://github.com/akshaysoftware/basis/commit/6938c5db489ddf2f044d62855355f335059635de)) +* fixed bug where arrays could only be initialised by literals ([#185](https://github.com/akshaysoftware/basis/issues/185)) ([4c676f3](https://github.com/akshaysoftware/basis/commit/4c676f3e60bec386cc99f1bbefbbc0cab71c59f3)) +* initialise m_state to a single amplitude ([#177](https://github.com/akshaysoftware/basis/issues/177)) ([b6d59e2](https://github.com/akshaysoftware/basis/commit/b6d59e232394be9583aaa4366cf96ba4eea5d4d1)) +* install scripts migrated to website, added update checker ([#184](https://github.com/akshaysoftware/basis/issues/184)) ([fee4115](https://github.com/akshaysoftware/basis/commit/fee411539b8778d3cc3550d7df23de1f4d725514)) +* optimise qasm logging for better performance ([#178](https://github.com/akshaysoftware/basis/issues/178)) ([a2b9cd4](https://github.com/akshaysoftware/basis/commit/a2b9cd4eb7c56efa215b3cf50675ad8278d618de)) +* parenthesised expressions not being evaluated at runtime ([#182](https://github.com/akshaysoftware/basis/issues/182)) ([68c6371](https://github.com/akshaysoftware/basis/commit/68c63719bc430da35315b4bffc9b5472298b2beb)) +* **perf:** made runtime evaluator single use to prevent state leakage ([#170](https://github.com/akshaysoftware/basis/issues/170)) ([87afa42](https://github.com/akshaysoftware/basis/commit/87afa428208e60bcada4ab4183399ad94ed4e88d)) +* reset now clears measured flag ([#172](https://github.com/akshaysoftware/basis/issues/172)) ([e07f9fd](https://github.com/akshaysoftware/basis/commit/e07f9fdd76c9a20e89ccd025aef92e6ae45e4e9f)) \ No newline at end of file diff --git a/CITATION.cff b/CITATION.cff index 87a95a0..debb4ee 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -3,7 +3,6 @@ authors: - family-names: Pal given-names: Akshay orcid: "https://orcid.org/0009-0004-0465-4420" -doi: 10.5281/zenodo.18407424 message: If you use this software, please cite our article in the Journal of Open Source Software. preferred-citation: @@ -24,5 +23,5 @@ preferred-citation: type: article url: "https://joss.theoj.org/papers/10.21105/joss.09625" volume: 11 -title: "Bloch: a strongly typed, hardware-agnostic, hybrid quantum - programming language" +title: "Basis" +url: "https://github.com/akshaysoftware/basis" diff --git a/CMakeLists.txt b/CMakeLists.txt index ccebb48..d9be1b2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,80 +1,54 @@ -cmake_minimum_required(VERSION 3.16) -project(bloch LANGUAGES CXX) - -set(CMAKE_CXX_STANDARD 20) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_EXPORT_COMPILE_COMMANDS ON) -set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) - -# Default to an optimised build when no build type is provided (matches packaged binaries) -if(NOT CMAKE_BUILD_TYPE) - set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE) -endif() -message(STATUS "CMAKE_BUILD_TYPE: ${CMAKE_BUILD_TYPE}") - - -# Determine version from CI tag or local git -set(BLOCH_VERSION "unknown") -if(DEFINED ENV{BLOCH_VERSION} AND NOT "$ENV{BLOCH_VERSION}" STREQUAL "") - # Explicit override (recommended in CI) - set(BLOCH_VERSION "$ENV{BLOCH_VERSION}") -elseif(DEFINED ENV{GITHUB_REF_NAME} AND NOT "$ENV{GITHUB_REF_NAME}" STREQUAL "") - # GitHub Actions tag name when building a tagged release - set(BLOCH_VERSION "$ENV{GITHUB_REF_NAME}") -elseif(DEFINED ENV{CI_COMMIT_TAG} AND NOT "$ENV{CI_COMMIT_TAG}" STREQUAL "") - # GitLab CI tag compatibility - set(BLOCH_VERSION "$ENV{CI_COMMIT_TAG}") -else() - find_package(Git QUIET) - if(GIT_FOUND) - execute_process( - COMMAND ${GIT_EXECUTABLE} describe --tags --always --dirty=-modified - WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} - OUTPUT_VARIABLE GIT_DESCRIBE - OUTPUT_STRIP_TRAILING_WHITESPACE - RESULT_VARIABLE GIT_DESCRIBE_RESULT - ) - if(GIT_DESCRIBE_RESULT EQUAL 0 AND NOT "${GIT_DESCRIBE}" STREQUAL "") - set(BLOCH_VERSION "${GIT_DESCRIBE}") - endif() - endif() +cmake_minimum_required(VERSION 3.28) + +project( + Basis + LANGUAGES CXX +) + +option( + BLOCH_WARNINGS_AS_ERRORS + "Treat compiler warnings as errors" + OFF +) + +add_library(bloch_project_warnings INTERFACE) +add_library(bloch::project_warnings ALIAS bloch_project_warnings) + +target_compile_options( + bloch_project_warnings + INTERFACE + "$<$:-Wall;-Wextra;-Wpedantic>" + "$<$:/W4;/permissive->" +) + +if(BLOCH_WARNINGS_AS_ERRORS) + target_compile_options( + bloch_project_warnings + INTERFACE + "$<$:-Werror>" + "$<$:/WX>" + ) endif() -message(STATUS "Bloch version: ${BLOCH_VERSION}") -# Capture short commit hash if available (best-effort) -set(BLOCH_COMMIT_HASH "unknown") -if(NOT GIT_FOUND) - find_package(Git QUIET) -endif() +file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/version.txt" BASIS_VERSION LIMIT_COUNT 1) +find_package(Git QUIET) +set(BASIS_COMMIT "unknown") if(GIT_FOUND) execute_process( - COMMAND ${GIT_EXECUTABLE} rev-parse --short HEAD - WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} - OUTPUT_VARIABLE BLOCH_COMMIT_HASH + COMMAND "${GIT_EXECUTABLE}" rev-parse --short HEAD + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + OUTPUT_VARIABLE BASIS_COMMIT OUTPUT_STRIP_TRAILING_WHITESPACE - RESULT_VARIABLE GIT_HASH_RESULT ) - if(NOT GIT_HASH_RESULT EQUAL 0 OR "${BLOCH_COMMIT_HASH}" STREQUAL "") - set(BLOCH_COMMIT_HASH "unknown") + if(NOT BASIS_COMMIT) + set(BASIS_COMMIT "unknown") endif() endif() -message(STATUS "Bloch commit: ${BLOCH_COMMIT_HASH}") - - -# Treat warnings as errors -if(CMAKE_BUILD_TYPE STREQUAL "Debug") - add_compile_options(-Wall -Wextra -Werror -pedantic) -endif() - -enable_testing() add_subdirectory(src) -add_subdirectory(tests) -# CPack packaging configuration (used in release builds) -set(CPACK_PACKAGE_NAME "bloch") -string(REGEX REPLACE "^v" "" CPACK_PACKAGE_VERSION "${BLOCH_VERSION}") -set(CPACK_PACKAGE_VENDOR "Bloch Labs") -set(CPACK_PACKAGE_CONTACT "hello@bloch-labs.com") -set(CPACK_DEBIAN_PACKAGE_MAINTAINER "Bloch Labs ") -include(CPack) +include(CTest) + +if(BUILD_TESTING) + add_subdirectory(tests) +endif() \ No newline at end of file diff --git a/CMakePresets.json b/CMakePresets.json new file mode 100644 index 0000000..2532a87 --- /dev/null +++ b/CMakePresets.json @@ -0,0 +1,82 @@ +{ + "version": 6, + "cmakeMinimumRequired": { + "major": 3, + "minor": 28, + "patch": 0 + }, + "configurePresets": [ + { + "name": "base", + "hidden": true, + "generator": "Ninja", + "binaryDir": "${sourceDir}/build/${presetName}", + "cacheVariables": { + "CMAKE_EXPORT_COMPILE_COMMANDS": "ON" + } + }, + { + "name": "dev", + "displayName": "Development", + "inherits": "base", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug", + "BLOCH_WARNINGS_AS_ERRORS": "OFF" + } + }, + { + "name": "ci", + "displayName": "Continuous Integration", + "inherits": "base", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release", + "BLOCH_WARNINGS_AS_ERRORS": "ON" + } + }, + { + "name": "release", + "inherits": "base", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release", + "BLOCH_WARNINGS_AS_ERRORS": "OFF" + } + } + ], + "buildPresets": [ + { + "name": "dev", + "configurePreset": "dev" + }, + { + "name": "ci", + "configurePreset": "ci" + }, + { + "name": "release", + "configurePreset": "release" + } + ], + "testPresets": [ + { + "name": "dev", + "configurePreset": "dev", + "output": { + "outputOnFailure": true + } + }, + { + "name": "ci", + "configurePreset": "ci", + "output": { + "outputOnFailure": true + } + }, + { + "name": "release", + "configurePreset": "release", + "output": { + "outputOnFailure": true + } + } + ] +} diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 30b8f2d..34bf425 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,95 +1,11 @@ -# Contributor Covenant 3.0 Code of Conduct +# Code of conduct -## Our Pledge +Treat contributors respectfully. Critique ideas and code constructively, welcome +questions, and respect people's privacy and boundaries. -We pledge to make our community welcoming, safe, and equitable for all. +Harassment, discrimination, threats, personal attacks and publication of private +information are unacceptable in project issues, pull requests and discussions. -We are committed to fostering an environment that respects and promotes the dignity, rights, and contributions of all individuals, regardless of characteristics including race, ethnicity, caste, colour, age, physical characteristics, neurodiversity, disability, sex or gender, gender identity or expression, sexual orientation, language, philosophy or religion, national or social origin, socio-economic position, level of education, or other status. The same privileges of participation are extended to everyone who participates in good faith and in accordance with this Covenant. - - -## Encouraged Behaviours - -While acknowledging differences in social norms, we all strive to meet our community's expectations for positive behaviour. We also understand that our words and actions may be interpreted differently than we intend based on culture, background, or native language. - -With these considerations in mind, we agree to behave mindfully toward each other and act in ways that centre our shared values, including: - -1. Respecting the **purpose of our community**, our activities, and our ways of gathering. -2. Engaging **kindly and honestly** with others. -3. Respecting **different viewpoints** and experiences. -4. **Taking responsibility** for our actions and contributions. -5. Gracefully giving and accepting **constructive feedback**. -6. Committing to **repairing harm** when it occurs. -7. Behaving in other ways that promote and sustain the **well-being of our community**. - - -## Restricted Behaviours - -We agree to restrict the following behaviours in our community. Instances, threats, and promotion of these behaviours are violations of this Code of Conduct. - -1. **Harassment.** Violating explicitly expressed boundaries or engaging in unnecessary personal attention after any clear request to stop. -2. **Character attacks.** Making insulting, demeaning, or pejorative comments directed at a community member or group of people. -3. **Stereotyping or discrimination.** Characterising anyone’s personality or behaviour on the basis of immutable identities or traits. -4. **Sexualisation.** Behaving in a way that would generally be considered inappropriately intimate in the context or purpose of the community. -5. **Violating confidentiality**. Sharing or acting on someone's personal or private information without their permission. -6. **Endangerment.** Causing, encouraging, or threatening violence or other harm toward any person or group. -7. Behaving in other ways that **threaten the well-being** of our community. - -### Other Restrictions - -1. **Misleading identity.** Impersonating someone else for any reason, or pretending to be someone else to evade enforcement actions. -2. **Failing to credit sources.** Not properly crediting the sources of content you contribute. -3. **Promotional materials**. Sharing marketing or other commercial content in a way that is outside the norms of the community. -4. **Irresponsible communication.** Failing to responsibly present content which includes, links or describes any other restricted behaviours. - - -## Reporting an Issue - -Tensions can occur between community members even when they are trying their best to collaborate. Not every conflict represents a code of conduct violation, and this Code of Conduct reinforces encouraged behaviours and norms that can help avoid conflicts and minimise harm. - -When an incident does occur, it is important to report it promptly. To report a possible violation, email **hello@bloch-labs.com** with the subject line "Code of Conduct" and include: -- a brief summary of what happened -- links or screenshots (if available) -- where and when it occurred -- any safety concerns or desired outcomes - -Bloch maintainers take reports seriously and will make every effort to respond in a timely manner. They will investigate all reports of code of conduct violations, reviewing messages, logs, and recordings, or interviewing witnesses and other participants. Maintainers will keep investigation and enforcement actions as transparent as possible while prioritising safety and confidentiality. In order to honour these values, enforcement actions are carried out in private with the involved parties, but communicating to the whole community may be part of a mutually agreed upon resolution. - - -## Addressing and Repairing Harm - -The remedies and repairs outlined below are guidelines. Maintainers may skip or combine steps based on severity, impact, or safety considerations. - -If an investigation by the maintainers finds that this Code of Conduct has been violated, the following enforcement ladder may be used to determine how best to repair harm, based on the incident's impact on the individuals involved and the community as a whole. Depending on the severity of a violation, lower rungs on the ladder may be skipped. - -1) Warning - 1) Event: A violation involving a single incident or series of incidents. - 2) Consequence: A private, written warning from the maintainers. - 3) Repair: Examples of repair include a private written apology, acknowledgement of responsibility, and seeking clarification on expectations. -2) Temporarily Limited Activities - 1) Event: A repeated incidence of a violation that previously resulted in a warning, or the first incidence of a more serious violation. - 2) Consequence: A private, written warning with a time-limited cooldown period designed to underscore the seriousness of the situation and give the community members involved time to process the incident. The cooldown period may be limited to particular communication channels or interactions with particular community members. - 3) Repair: Examples of repair may include making an apology, using the cooldown period to reflect on actions and impact, and being thoughtful about re-entering community spaces after the period is over. -3) Temporary Suspension - 1) Event: A pattern of repeated violation which the Community Moderators have tried to address with warnings, or a single serious violation. - 2) Consequence: A private written warning with conditions for return from suspension. In general, temporary suspensions give the person being suspended time to reflect upon their behaviour and possible corrective actions. - 3) Repair: Examples of repair include respecting the spirit of the suspension, meeting the specified conditions for return, and being thoughtful about how to reintegrate with the community when the suspension is lifted. -4) Permanent Ban - 1) Event: A pattern of repeated code of conduct violations that other steps on the ladder have failed to resolve, or a violation so serious that the Community Moderators determine there is no way to keep the community safe with this person as a member. - 2) Consequence: Access to all community spaces, tools, and communication channels is removed. In general, permanent bans should be rarely used, should have strong reasoning behind them, and should only be resorted to if working through other remedies has failed to change the behaviour. - 3) Repair: There is no possible repair in cases of this severity. - -This enforcement ladder is intended as a guideline. It does not limit the ability of maintainers to use their discretion and judgment, in keeping with the best interests of our community. - - -## Scope - -This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public or other spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. - - -## Attribution - -This Code of Conduct is adapted from the Contributor Covenant, version 3.0, permanently available at [https://www.contributor-covenant.org/version/3/0/](https://www.contributor-covenant.org/version/3/0/). - -Contributor Covenant is stewarded by the Organization for Ethical Source and licensed under CC BY-SA 4.0. To view a copy of this licence, visit [https://creativecommons.org/licenses/by-sa/4.0/](https://creativecommons.org/licenses/by-sa/4.0/) - -For answers to common questions about Contributor Covenant, see the FAQ at [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq). Translations are provided at [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations). Additional enforcement and community guideline resources can be found at [https://www.contributor-covenant.org/resources](https://www.contributor-covenant.org/resources). The enforcement ladder was inspired by the work of [Mozilla’s code of conduct team](https://github.com/mozilla/inclusion). +Report concerns privately to akshay.anu@gmail.com. The maintainer will review reports +discreetly and may remove content, restrict participation or block accounts when +needed to protect the community. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bb4bf53..02e3a8b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,40 +1,47 @@ -# Contributing +# Contributing to Basis -Thanks for your interest in contributing to Bloch! Please check the issues tab for open work -or file a new issue if you spot a bug or have an idea. +Bug reports, documentation improvements and focused code contributions are welcome. +Discuss significant language or architecture changes in an issue before implementing them. -## Start here -- `engineering/reference/how-to-contribute.md` -- `engineering/reference/codebase-overview.md` +## Set up -## Building from source +Install a C++20 compiler, CMake 3.28+, Ninja, Bash, just and clang-format 18. +Fork the repository if you do not have write access, then clone your fork. -### Linux/macOS ```bash -git clone https://github.com/bloch-labs/bloch.git -cd bloch -cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -cmake --build build --parallel -ctest --test-dir build --output-on-failure +git clone https://github.com/YOUR-USERNAME/basis.git +cd basis +git remote add upstream https://github.com/akshaysoftware/basis.git +git switch -c fix/describe-the-change +just build ``` -Run the compiler against an example with `./build/bin/bloch examples/02_bell_state.bloch`. +## Development -### Windows (Visual Studio) -```powershell -git clone https://github.com/bloch-labs/bloch.git -cd bloch -cmake -S . -B build -G "Visual Studio 17 2022" -A x64 -DCMAKE_BUILD_TYPE=Release -cmake --build build --config Release --parallel -ctest --test-dir build --config Release --output-on-failure +`main` is the trunk. Create a short-lived branch for each change and open a PR to +`main`. Keep changes focused and add regression coverage for changed behaviour. + +```bash +just format +just check +git diff --check ``` -This produces a `build/Bloch.sln` you can open directly in Visual Studio for editing and -debugging. The `bloch.exe` binary is placed in `build/bin/Release/`. +`just check` checks formatting, builds with warnings as errors, runs tests and +examples, and checks an installation from outside the source checkout. +See [the C++ style guide](docs/cpp-style.md) and [architecture](docs/architecture.md). + +Use a Conventional Commit PR title, for example `fix: reject invalid gate operands`, +`feat: add seeded simulation` or `docs: clarify module imports`. +PRs are squash merged; their title becomes the commit title. + +After your PR merges, delete the feature branch and update from `main`. +For substantial behaviour changes, update the relevant documentation and changelog. + +## Reporting problems -## Documentation expectations +Include the Basis version or commit, operating system, command, minimal program, +expected result and actual diagnostic. Follow [SECURITY.md](SECURITY.md) for private +security reports and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) in project spaces. -When behaviour changes, update the matching docs in the same pull request: -- User docs: `docs/` -- Contributor references: `engineering/reference/` -- Design/decision records when architecture intent changes: `engineering/designs/` and `engineering/adrs/` +Contributions are made under the project's Apache-2.0 license. diff --git a/README.md b/README.md index 91d239c..8dcd8d4 100644 --- a/README.md +++ b/README.md @@ -1,54 +1,86 @@ -> [!IMPORTANT] -> **This repository contains the archived original implementation of the Bloch programming language and is no longer under active development.** -> -> The original `v1.0.x` release line is preserved here as part of Bloch's development and research history. Bloch `v1.0.3` is the software release associated with the 2026 Journal of Open Source Software publication and is permanently archived as Zenodo DOI `10.5281/zenodo.18407424`. -> -> Active development of Bloch restarted in August 2026 in [`bloch-labs/bloch-lang`](https://github.com/bloch-labs/bloch-lang), using a pre-1.0 versioning policy while the language architecture, package model and compiler interfaces are stabilised. -> -> JOSS paper DOI: `10.21105/joss.09625` -> -> --- - -# Bloch - -Bloch is an open-source, strongly typed, hybrid quantum programming language. It’s designed for people who want classical and quantum code side by side. The toolchain is hardware-agnostic so you can move between simulators and future backends. - -## 🚀 Install -- Linux/macOS: +# Basis + +[![CI](https://github.com/akshaysoftware/basis/actions/workflows/ci.yml/badge.svg)](https://github.com/akshaysoftware/basis/actions/workflows/ci.yml) +[![License: Apache-2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](LICENSE) + +Basis is an open-source, typed language for hybrid classical and quantum programs, +implemented in C++20 and maintained by [Akshay Pal](https://github.com/akshaysoftware). + +The project is developing towards version 2.0. Language and compiler interfaces may +change. The current toolchain retains the `.bloch` source extension and `bloch.lang` +standard-library namespace from its predecessor. + +## Build and run + +Requirements: a C++20 compiler, CMake 3.28+, Ninja and Bash. Contributor commands also +use [just](https://just.systems) and clang-format 18. + +```bash +git clone https://github.com/akshaysoftware/basis.git +cd basis +just build +just run examples/02_bell_state.bloch --shots=1000 +just test +``` + +A small program looks like this: + +```text +function main() -> void { + @tracked qubit[2] q; + h(q[0]); + cx(q[0], q[1]); + measure q; +} ``` -curl -fsSL https://raw.githubusercontent.com/bloch-labs/bloch/HEAD/scripts/install.sh | bash -s -- latest + +## Install from source + +From a checkout on macOS or Linux: + +```bash +bash scripts/install.sh +export PATH="$HOME/.local/bin:$PATH" +basis --version ``` -Swap `latest` for a specific tag (eg `v1.1.0`). The script downloads the matching archive for your platform, verifies its checksum, installs the `bloch` binary into a writable directory, installs the bundled stdlib to your user data directory (for immediate `bloch.lang` usage), and updates your shell profile if needed. Add `INSTALL_DIR=/custom/path` before `bash` to override the binary destination. -#### Windows -```powershell -powershell -NoProfile -ExecutionPolicy Bypass -Command "iwr https://raw.githubusercontent.com/bloch-labs/bloch/HEAD/scripts/install.ps1 -UseBasicParsing -OutFile $env:TEMP\\bloch-install.ps1; & $env:TEMP\\bloch-install.ps1 -Version latest" +The installer builds and tests the current checkout, then installs the executable +and bundled standard library under `~/.local`. Pass an absolute prefix to change it: + +```bash +bash scripts/install.sh /absolute/install/prefix ``` -Swap `-Version latest` for any tag you want. The script downloads the Windows ZIP, verifies its checksum, installs `bloch.exe` into `%LOCALAPPDATA%\Programs\Bloch` by default, installs stdlib files to `%LOCALAPPDATA%\Bloch\library`, and adds the binary directory to your user `PATH` (opens in new shells). -You can self-update later with `bloch --update`; major version jumps prompt for confirmation and show the changelog link. +## Documentation and contributions + +- [Documentation](docs/README.md) +- [Contributing](CONTRIBUTING.md) +- [Code of conduct](CODE_OF_CONDUCT.md) +- [Security reports](SECURITY.md) +- [Issues](https://github.com/akshaysoftware/basis/issues) + +Run `just` to list development commands and `just check` before opening a PR. +Development uses short-lived feature branches and squash merges into `main`. + +## Current limitations -- From source: See `CONTRIBUTING.md` +The simulator's reset behaviour on entangled states requires correction. OpenQASM +2 output is an execution trace and does not preserve general measurement-dependent +control flow. Sampling does not yet expose a seed option. Treat these as development +limitations when evaluating results. See [known issues](docs/known-issues.md). -## 💻 VS Code Extension -Syntax highlighting: https://github.com/bloch-labs/bloch-vscode +## History and citation -## 📚 Documentation -- User docs: `docs/README.md` -- Contributor docs: `engineering/reference/README.md` +Basis continues the Bloch programming-language project in its original repository. +Bloch v1.0.3 accompanies the 2026 JOSS paper: -## 📝 Cite -Use `CITATION.cff` (GitHub’s “Cite this repository” button) for BibTeX/metadata. +Pal, A. (2026). *Bloch: a strongly typed, hardware-agnostic, hybrid quantum +programming language*. Journal of Open Source Software, 11(117), 9625. +[Paper](https://doi.org/10.21105/joss.09625) · +[Archived software](https://doi.org/10.5281/zenodo.18407424). -## 🤝 Contributing -Thanks for your interest in contributing! Check the issues tab and read `CONTRIBUTING.md` plus the contributor docs before raising a PR. +The paper describes the historical release. See [CITATION.cff](CITATION.cff). -## 🌐 Community -You can follow along our journey via the following community links: -- Website: https://bloch-labs.com -- Substack: https://blochlabs.substack.com/subscribe -- X/Twitter: https://x.com/blochlabs -- Email: hello@bloch-labs.com +## License -## 📄 Licence -Apache 2.0 (see `LICENSE`). +[Apache License 2.0](LICENSE). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..235fb2c --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,12 @@ +# Security + +Report suspected vulnerabilities using GitHub's private vulnerability reporting: +[Report a vulnerability](https://github.com/akshaysoftware/basis/security/advisories/new). +If that option is unavailable, email akshay.anu@gmail.com. + +Include the affected commit or version, a minimal reproduction and the impact. +Please avoid publishing exploit details before the report has been assessed. + +Security fixes target the current development branch. Historical v1 releases are +preserved for reproducibility and do not have a separate maintenance commitment. +General language and simulator correctness bugs belong in the public issue tracker. diff --git a/docs/README.md b/docs/README.md index b81065f..8aa3ef9 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,33 +1,18 @@ -# Bloch Documentation +# Basis documentation -See [CHANGELOG](../CHANGELOG.md) for release history and version-specific changes. For a contributor reference guide, see `engineering/reference/README.md`. +The reference describes the inherited language while v2 development is underway. +The source extension remains `.bloch`, and the standard library uses `bloch.lang`. -## Start here -- [Overview: What is Bloch?](./overview.md) -- [Getting Started](./getting-started.md) -- [Language Tour](./language-tour.md) +- [Getting started](getting-started.md) +- [Language specification](language-spec.md) +- [Grammar](grammar.md) +- [Quantum programming](quantum-programming.md) +- [Classes and objects](classes-and-objects.md) +- [Functions and modules](functions-and-modules.md) +- [CLI](tooling-and-cli.md) +- [Diagnostics](diagnostics.md) +- [Known issues](known-issues.md) +- [Architecture](architecture.md) +- [C++ conventions](cpp-style.md) -## Language reference -- [Language Specification](./language-spec.md) -- [Grammar (EBNF)](./grammar.md) -- [Runtime Model](./runtime.md) -- [Errors & Diagnostics](./diagnostics.md) - -## Guides -- [Types and Data](./types-and-data.md) -- [Control Flow](./control-flow.md) -- [Functions and Modules](./functions-and-modules.md) -- [Classes and Objects](./classes-and-objects.md) -- [Casting](./casting.md) -- [Quantum Programming](./quantum-programming.md) -- [Annotations & Tracking](./annotations-and-tracking.md) -- [Tooling & CLI](./tooling-and-cli.md) -- [Built-ins and Quantum Gates](./builtins-and-gates.md) -- [Examples](./examples.md) -- [Troubleshooting](./troubleshooting.md) - -## Where to go next - -- **New to quantum?** [Getting Started](./getting-started.md) → [Quantum Programming](./quantum-programming.md) → [Examples](./examples.md) (try 01, 02, then 05). -- **Language depth:** [Types and Data](./types-and-data.md) → [Control Flow](./control-flow.md) → [Functions and Modules](./functions-and-modules.md) → [Classes and Objects](./classes-and-objects.md). -- **Reference:** [Language Specification](./language-spec.md), [Grammar](./grammar.md), [Runtime Model](./runtime.md), [Errors & Diagnostics](./diagnostics.md). +Contributor workflow: [CONTRIBUTING.md](../CONTRIBUTING.md). diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..a527ee8 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,15 @@ +# Architecture + +- `src/bloch/compiler`: lexer, parser, AST, imports and semantic analysis. +- `src/bloch/runtime`: program evaluation, statevector simulation and tracing. +- `src/bloch/cli`: arguments, execution and output. +- `library/bloch/lang`: bundled standard library. +- `tests`: unit and CLI integration tests. +- `examples`: executable language examples. + +The internal `bloch` namespace and source extension remain for compatibility during +the restart. User-facing commands and installation paths use `basis`. + +CMake builds compiler, runtime and CLI libraries plus the `basis` executable. +CTest runs the test executable. `just check` also exercises examples and an installed +copy from a separate working directory. diff --git a/docs/builtins-and-gates.md b/docs/builtins-and-gates.md index 3993dab..960ebfe 100644 --- a/docs/builtins-and-gates.md +++ b/docs/builtins-and-gates.md @@ -1,6 +1,6 @@ # Built-ins and Quantum Gates -This page is the single reference for built-in functions and quantum operations in Bloch. For full language rules, see the [Language Specification](./language-spec.md). +This page is the single reference for built-in functions and quantum operations in Basis. For full language rules, see the [Language Specification](./language-spec.md). ## Built-in function diff --git a/docs/casting.md b/docs/casting.md index e45fc9a..aa7b8cd 100644 --- a/docs/casting.md +++ b/docs/casting.md @@ -1,6 +1,6 @@ # Casting -Bloch supports explicit casts using parentheses and performs implicit float promotion for +Basis supports explicit casts using parentheses and performs implicit float promotion for division (for example, `1/2` yields `0.5f`). ## Syntax diff --git a/docs/classes-and-objects.md b/docs/classes-and-objects.md index ece9392..9050b03 100644 --- a/docs/classes-and-objects.md +++ b/docs/classes-and-objects.md @@ -1,6 +1,6 @@ # Classes and Objects -Bloch v1.1.0 includes a class system with single inheritance, visibility, virtual dispatch, +Basis v1.1.0 includes a class system with single inheritance, visibility, virtual dispatch, and generics. Every non-static class implicitly extends `Object`. When the stdlib is installed, that root diff --git a/docs/control-flow.md b/docs/control-flow.md index 95c9399..eae208c 100644 --- a/docs/control-flow.md +++ b/docs/control-flow.md @@ -1,6 +1,6 @@ # Control Flow -Bloch uses familiar C-style control flow. Conditions must be `boolean` or `bit` (official recommendation is to always use `boolean` for conditional logic). +Basis uses familiar C-style control flow. Conditions must be `boolean` or `bit` (official recommendation is to always use `boolean` for conditional logic). ## Branching ```bloch @@ -18,7 +18,7 @@ for (int i = 0; i < 3; i = i + 1) { ... } while (keepGoing) { ... } ``` -Bloch does not currently support `break` or `continue`, so structure loops accordingly. +Basis does not currently support `break` or `continue`, so structure loops accordingly. ## Returns ```bloch diff --git a/docs/cpp-style.md b/docs/cpp-style.md new file mode 100644 index 0000000..62c7319 --- /dev/null +++ b/docs/cpp-style.md @@ -0,0 +1,396 @@ +# Basis C++ Style Guide + +This document defines the C++ conventions used by Basis. + +The goal is not to create an exhaustive set of rules. Code should be readable, predictable, +safe and straightforward to maintain. Where this guide does not specify a convention, prefer +established modern C++ practices and consistency with the surrounding code. + +## C++ version + +Basis targets **C++20**. + +Compiler-specific language extensions should not be used unless there is a clear portability +reason for doing so. + +All supported code should compile with: + +- GCC +- Clang +- AppleClang +- MSVC + +Cross-platform support will be enforced progressively through CI. + +## Formatting + +`clang-format` is the source of truth for C++ formatting. + +Do not manually format code in a way that conflicts with `.clang-format`. + +Format the source tree with: + +```bash +find src tests \ + -type f \ + \( -name '*.cpp' -o -name '*.hpp' -o -name '*.h' \) \ + -print0 \ + | xargs -0 clang-format -i +``` + +The configured maximum line length is 100 characters. + +Use four spaces for indentation. Do not use tabs. + +## Naming + +### Files + +Use `snake_case` for C++ filenames. + +```text +semantic_analyser.cpp +semantic_analyser.hpp +module_loader.cpp +token.hpp +``` + +Header files should normally use `.hpp`. + +### Namespaces + +Namespaces use lowercase `snake_case`. + +```cpp +namespace bloch { +namespace bloch::compiler { +namespace bloch::runtime { +``` + +Prefer nested namespace syntax: + +```cpp +namespace bloch::compiler { + +} // namespace bloch::compiler +``` + +### Types + +Classes, structs, enums and type aliases use `PascalCase`. + +```cpp +class SemanticAnalyser; +struct SourceLocation; +enum class TokenType; +using SymbolTable = std::unordered_map; +``` + +### Functions + +Functions and methods use `snake_case`. + +```cpp +parse_expression(); +resolve_symbol(); +lower_function(); +``` + +### Variables + +Local variables and function parameters use `snake_case`. + +```cpp +token_index +source_location +function_type +``` + +### Data members + +Private data members use `snake_case` with a trailing underscore. + +```cpp +class Parser { +private: + std::vector tokens_; + std::size_t current_; +}; +``` + +Do not introduce Hungarian-style prefixes such as `m_`. + +Existing legacy code using older conventions may be migrated incrementally. + +### Constants + +Compile-time constants use a `k` prefix followed by `PascalCase`. + +```cpp +inline constexpr std::size_t kMaximumQubits = 64; +``` + +### Enum values + +Scoped enum values use `PascalCase`. + +```cpp +enum class TokenType { + Identifier, + IntegerLiteral, + EndOfFile +}; +``` + +Always prefer `enum class` over unscoped enums. + +## Ownership and memory + +Ownership should always be clear from the type. + +Use `std::unique_ptr` for exclusive ownership. + +```cpp +std::unique_ptr +``` + +Use references for required non-owning access. + +```cpp +const SymbolTable& symbols +``` + +Use raw pointers only for explicitly non-owning or nullable relationships. + +```cpp +const Symbol* parent = nullptr; +``` + +Use `std::shared_ptr` only when ownership is genuinely shared. + +Do not use `std::shared_ptr` simply because ownership is unclear. + +Prefer RAII. Avoid direct use of `new`, `delete`, `malloc` or `free` unless implementing +genuinely low-level functionality where higher-level ownership types are unsuitable. + +## Standard library + +Prefer standard library types and algorithms over custom equivalents. + +Use modern C++ vocabulary types where their semantics are appropriate: + +```cpp +std::optional +std::variant +std::unique_ptr +std::string_view +std::span +std::filesystem::path +``` + +Do not use a type merely because it is modern. The type should accurately express the intended +ownership and lifetime semantics. + +## `auto` + +Use `auto` when it improves readability or avoids repeating an obvious or verbose type. + +Good: + +```cpp +auto token = lexer.next_token(); +auto iterator = symbols.find(name); +``` + +Prefer an explicit type when the type communicates important information to the reader. + +## `const` + +Use `const` wherever an object is not intended to be modified. + +Methods that do not mutate observable object state should be marked `const`. + +```cpp +[[nodiscard]] bool has_errors() const; +``` + +## `[[nodiscard]]` + +Use `[[nodiscard]]` when ignoring a return value is likely to represent a programming error. + +Good candidates include: + +- parse operations +- lookup operations +- validation operations +- predicates whose result must normally be considered + +Do not add it mechanically to every function returning a value. + +## `constexpr` + +Use `constexpr` for values and functions that are meaningfully compile-time constructs. + +Do not use it purely as decoration. + +## `noexcept` + +`noexcept` is a semantic guarantee. + +Only mark functions `noexcept` when the implementation can genuinely uphold that guarantee. + +## Headers + +Headers must be self-contained. + +A header should compile correctly when included without relying on another file having already +included one of its dependencies. + +Include what you use. + +Do not place `using namespace` directives in header files. + +Prefer forward declarations when they meaningfully reduce coupling, but do not sacrifice +clarity merely to minimise includes. + +Use: + +```cpp +#pragma once +``` + +for include protection. + +## Includes + +Allow `clang-format` to order include groups. + +Prefer this broad ordering: + +1. the corresponding header for a `.cpp` file +2. C++ standard library headers +3. project headers + +Example: + +```cpp +#include "bloch/compiler/parser/parser.hpp" + +#include +#include +#include + +#include "bloch/compiler/lexer/token.hpp" +#include "bloch/support/error/bloch_error.hpp" +``` + +## Control flow + +Prefer explicit control flow over clever expressions. + +Use braces for control-flow bodies, including single-statement bodies. + +Preferred: + +```cpp +if (tokens.empty()) { + return; +} +``` + +rather than: + +```cpp +if (tokens.empty()) + return; +``` + +Early returns are encouraged when they reduce nesting. + +## Error handling + +Compiler and runtime errors caused by Basis Basis programs should use the diagnostic/error provided at `bloch/support/error/bloch_error.hpp`. + +Exceptions may be used for exceptional failure paths. + +Do not use exceptions for ordinary control flow. + +Internal programming errors should fail clearly rather than silently continuing in an invalid +state. + +## Comments + +Comments should explain **why**, not restate **what** the code already says. + +Avoid comments such as: + +```cpp +// Increment i +++i; +``` + +Useful comments explain constraints, invariants, surprising behaviour or architectural +decisions. + +Public APIs and non-obvious compiler components should receive concise documentation where +necessary. + +## Functions + +Prefer small functions with a single clear responsibility. + +Avoid large functions that mix parsing, validation, transformation and output where those +responsibilities can be expressed independently. + +Function parameters should make ownership expectations obvious through their types. + +## Classes + +Keep classes focused on one responsibility. + +Prefer composition over inheritance unless inheritance models a genuine type relationship. + +Make constructors `explicit` when a single-argument constructor should not provide an implicit +conversion. + +```cpp +explicit Parser(std::vector tokens); +``` + +## CMake + +Basis uses target-based CMake. + +Prefer: + +```cmake +target_compile_features(...) +target_compile_options(...) +target_include_directories(...) +target_link_libraries(...) +``` + +over global build configuration. + +Avoid global commands such as: + +```cmake +add_compile_options(...) +include_directories(...) +``` + +when the setting belongs to a particular target. + +Each compiler component should declare its own dependencies. + +## Legacy code + +The initial compiler implementation was imported from `akshaysoftware/basis`. + +Imported code does not necessarily comply with every convention in this guide. + +Do not perform large mechanical rewrites solely for stylistic consistency unless there is a +clear engineering benefit. + +New code should follow this guide, and legacy code should be migrated incrementally when it is +already being modified or when a focused refactoring provides clear value. \ No newline at end of file diff --git a/docs/diagnostics.md b/docs/diagnostics.md index 5daeaa2..a25eee6 100644 --- a/docs/diagnostics.md +++ b/docs/diagnostics.md @@ -1,6 +1,6 @@ # Errors & Diagnostics -The Bloch interpreter reports errors with 1-based line and column numbers. It exits with a non-zero code on lexical, parse, semantic, or runtime errors. +The Basis interpreter reports errors with 1-based line and column numbers. It exits with a non-zero code on lexical, parse, semantic, or runtime errors. ## Reading error messages diff --git a/docs/examples.md b/docs/examples.md index 94c9c96..8433450 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -38,13 +38,13 @@ function main() -> void { **Run (installed):** ```bash -bloch examples/01_hadamard.bloch +basis examples/01_hadamard.bloch ``` **Run (from source, repo root):** ```bash -./build/bin/bloch examples/01_hadamard.bloch +./build/dev/bin/basis examples/01_hadamard.bloch ``` **Sample output:** A single bit, e.g. `0` or `1`, plus tracked summary if multiple shots are used. @@ -74,13 +74,13 @@ function main() -> void { **Run:** ```bash -bloch examples/02_bell_state.bloch +basis examples/02_bell_state.bloch ``` Or with QASM printed to stdout: ```bash -bloch examples/02_bell_state.bloch --emit-qasm +basis examples/02_bell_state.bloch --emit-qasm ``` **Sample output:** A two-bit result such as `[0, 0]` or `[1, 1]` (correlated). @@ -109,13 +109,13 @@ function main() -> void { **Run:** Pass the file that contains `main()` (the entry point). From the repo root: ```bash -bloch examples/multifile/main.bloch +basis examples/multifile/main.bloch ``` Or with a built-from-source binary: ```bash -./build/bin/bloch examples/multifile/main.bloch +./build/dev/bin/basis examples/multifile/main.bloch ``` The module loader resolves imports relative to the importing file first, then configured search @@ -128,7 +128,7 @@ If you don’t have `bloch` on your PATH, build then run with the built binary: ```bash cmake -S . -B build -DCMAKE_BUILD_TYPE=Release cmake --build build --parallel -./build/bin/bloch examples/02_bell_state.bloch --emit-qasm +./build/dev/bin/basis examples/02_bell_state.bloch --emit-qasm ``` Use `--echo=all` for verbose output during multi-shot runs. diff --git a/docs/functions-and-modules.md b/docs/functions-and-modules.md index 640817e..56ac854 100644 --- a/docs/functions-and-modules.md +++ b/docs/functions-and-modules.md @@ -10,7 +10,7 @@ initialisation. Top-level functions are not overloadable. ## Annotations - `@quantum` marks functions that run quantum code and must return `bit`, `bit[]`, or `void`. -- `@shots(N)` applies to `main()` to run multiple shots without passing `--shots=N` (CLI flag to be deprecated in v2.0.0). +- `@shots(N)` applies to `main()` to run multiple shots without passing `--shots=N`. `@quantum` may not decorate `main()`. diff --git a/docs/getting-started.md b/docs/getting-started.md index 2306346..19008ee 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -1,123 +1,12 @@ -# Getting Started -**About 5 minutes.** +# Getting started -This quick guide helps you install Bloch and run your first program. By the end you'll have run a classical "Hello, Bloch!" program and a simple quantum program that emits OpenQASM 2.0. - -## Prerequisites - -- **Supported platforms:** Linux, macOS and Windows. -- **Optional:** [VS Code](https://code.visualstudio.com/) is the recommended IDE with the [Bloch extension](https://github.com/bloch-labs/bloch-vscode) for syntax highlighting. -- **From source only:** [CMake](https://cmake.org/) and a C++17-capable toolchain (e.g. GCC, Clang). - -## Install - -Linux/macOS: - -```bash -curl -fsSL https://raw.githubusercontent.com/bloch-labs/bloch/HEAD/scripts/install.sh | bash -s -- latest -``` - -Windows (PowerShell): - -```bash -powershell -NoProfile -ExecutionPolicy Bypass -Command "iwr https://raw.githubusercontent.com/bloch-labs/bloch/HEAD/scripts/install.ps1 -UseBasicParsing -OutFile $env:TEMP\\bloch-install.ps1; & $env:TEMP\\bloch-install.ps1 -Version latest" -``` - -From source: - -```bash -git clone https://github.com/bloch-labs/bloch.git -cd bloch -cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -cmake --build build --parallel -ctest --test-dir build --output-on-failure -``` - -Verify the install: - -```bash -bloch --version -``` - -## Run your first program - -Run a shipped example to confirm everything works. From the repo root (if you have the repo), or using an installed `bloch` with a path to the example file: - -```bash -bloch examples/01_hadamard.bloch -``` - -If you built from source and are in the repo: - -```bash -./build/bin/bloch examples/01_hadamard.bloch -``` - -You should see a single measured bit (0 or 1). For more examples, see [Examples](./examples.md). - -## Hello, Bloch - -Create `hello.bloch`: - -```bloch -function main() -> void { - echo("Hello, Bloch!"); -} -``` - -Run it: - -```bash -bloch hello.bloch -``` - -## First quantum program - -The program below applies a Hadamard gate to one qubit and measures it. **`h(q)`** applies the Hadamard gate, putting the qubit into an equal superposition of \|0⟩ and \|1⟩. **OpenQASM** is a standard intermediate representation for quantum circuits; **`--emit-qasm`** prints the generated circuit to stdout (the runtime also writes `.qasm` next to your source). - -```bloch -@quantum -function flip() -> bit { - qubit q; - h(q); - return measure q; -} - -function main() -> void { - bit b = flip(); - echo("Measured: " + b); -} -``` - -Emit OpenQASM: +Follow the [README](../README.md) to build or install Basis from source. ```bash -bloch --emit-qasm flip.bloch +just run examples/01_hadamard.bloch --shots=1000 +just run examples/02_bell_state.bloch --shots=1000 ``` -## Multi-shot runs and tracking - -Annotate qubits with `@tracked` and run multiple shots to aggregate outcomes. - -```bloch -@shots(100) -function main() -> void { - @tracked qubit q; - h(q); - measure q; -} -``` - -Run: -```bash -bloch tracked.bloch -``` - -You can also use the CLI flag `--shots=100` if you prefer (however this will be deprecated in v2.0.0). - -## Next steps - -- Read the [Language Tour](./language-tour.md). -- Use the [Language Specification](./language-spec.md) as the authoritative reference. -- See [Built-ins and Quantum Gates](./builtins-and-gates.md) for `echo`, gates, and `measure`/`reset`. -- Explore [Examples](./examples.md). +Use `just run --help` for CLI options. The files in `examples/` demonstrate the +current language; `10_destructor_runtime_error.bloch` intentionally reports an error. +Read [known issues](known-issues.md) before relying on simulator or export results. diff --git a/docs/grammar.md b/docs/grammar.md index a48b0f7..40e5a4f 100644 --- a/docs/grammar.md +++ b/docs/grammar.md @@ -1,4 +1,4 @@ -# Bloch Grammar (EBNF) +# Basis Grammar (EBNF) This grammar reflects the current parser. Some constraints (such as valid type casts, `@shots` placement, or `super(...)` rules) are enforced semantically; see `language-spec.md`. diff --git a/docs/known-issues.md b/docs/known-issues.md new file mode 100644 index 0000000..8ad66ec --- /dev/null +++ b/docs/known-issues.md @@ -0,0 +1,12 @@ +# Known development issues + +- Resetting an entangled qubit can incorrectly bias the state of other qubits. +- Two-qubit gates currently accept identical control and target operands. +- OpenQASM 2 output records one executed path, including the final shot's path in + multi-shot runs. It does not preserve general measurement-dependent control flow. +- Sampling has no public seed option. +- Malformed `--shots` values need stricter validation and can terminate the CLI. + +These behaviours require focused fixes with regression coverage before a stable v2 +release. The unmerged QASM3 work remains archived on the restart repository's feature +branch until its export semantics are reviewed. diff --git a/docs/language-spec.md b/docs/language-spec.md index f14a768..05bf418 100644 --- a/docs/language-spec.md +++ b/docs/language-spec.md @@ -1,6 +1,6 @@ -# Bloch Language Specification +# Basis Language Specification -This document defines the Bloch language as implemented on this branch. Released versions are +This document defines the Basis language as implemented on this branch. Released versions are tracked in `CHANGELOG.md`. It is the normative reference; the other guides in this folder are explanatory. @@ -130,7 +130,7 @@ Key rules: - `destroy expr;` requires a class reference or `null`. ## Expressions and operators -Bloch uses C-style precedence and left-to-right evaluation for most operators. Highlights: +Basis uses C-style precedence and left-to-right evaluation for most operators. Highlights: - Arithmetic: `+ - * /` on numeric types (`int`, `long`, `float`). `%` is integer-only (`int` or `long`). `/` always returns `float`. @@ -189,5 +189,5 @@ For a single reference with descriptions, see [Built-ins and Quantum Gates](./bu explicitly request `--echo=all`. ## Errors -Bloch reports lexical, parse, semantic, and runtime errors with 1-based line and column numbers. +Basis reports lexical, parse, semantic, and runtime errors with 1-based line and column numbers. Runtime errors include invalid casts, division by zero, illegal member access, and qubit misuse. diff --git a/docs/language-tour.md b/docs/language-tour.md index e94e8ca..3e3fa49 100644 --- a/docs/language-tour.md +++ b/docs/language-tour.md @@ -1,11 +1,11 @@ # Language Tour -This is a fast walk through Bloch syntax with small, runnable snippets. +This is a fast walk through Basis syntax with small, runnable snippets. Start with the entry point: ```bloch function main() -> void { - echo("Hello, Bloch!"); + echo("Hello, Basis!"); } ``` diff --git a/docs/overview.md b/docs/overview.md index 4c3926b..a609ec8 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -1,23 +1,10 @@ -# What is Bloch? +# Basis -Bloch is an open-source, strongly typed **hybrid quantum programming language**. It lets you write classical and quantum code side by side in one language, with a single toolchain that stays **hardware-agnostic** so you can move between simulators and future quantum backends. +Basis is a typed language and interpreter for small hybrid classical and quantum +programs. It combines classical control flow with explicit qubits, gate operations, +measurement and local statevector simulation in a C++20 toolchain. -## Why Bloch? - -- **Hybrid by design** — Use familiar control flow, types, and functions for classical logic; declare qubits and gates explicitly for quantum circuits. No need to stitch two languages together. -- **Strong typing** — Explicit types for parameters, returns, and variables reduce mistakes and make intent clear. The compiler catches many errors before you run, saving you expensive quantum compute time. -- **OpenQASM emission** — Every run produces OpenQASM 2.0 (and OpenQASM 3.0 soon), so you can inspect the generated circuit and integrate with tools that consume QASM. -- **Ideal simulator** — The built-in statevector simulator gives exact results for algorithm development and education; you can extend or replace the backend later. - -## Typical use cases - -- **Learning quantum computing** — Write small circuits (Hadamard, Bell states, simple algorithms) and see results and QASM in one place. -- **Algorithm prototyping** — Implement and debug quantum algorithms with classical scaffolding (e.g. teleportation, Grover, MaxCut) and multi-shot statistics. -- **Research and teaching** — Share readable, typed code and reproducible QASM output with collaborators or students. -- **Quantum application development** — Design and build real quantum applications. - -## Next steps - -- [Getting Started](./getting-started.md) — Install Bloch and run your first program (about 5 minutes). -- [Language Tour](./language-tour.md) — A quick walk through Bloch syntax. -- [Quantum Programming](./quantum-programming.md) — Qubits, gates, and `@quantum` functions. +The current development priorities are simulator correctness, reproducible sampling, +clear diagnostics and a well-defined circuit-export contract. +See [known issues](known-issues.md), [getting started](getting-started.md) and +[the language specification](language-spec.md). diff --git a/docs/quantum-programming.md b/docs/quantum-programming.md index 4fa71cb..99d3c75 100644 --- a/docs/quantum-programming.md +++ b/docs/quantum-programming.md @@ -1,6 +1,6 @@ # Quantum Programming -Bloch treats quantum data explicitly. Declare qubits with `qubit q;` or `qubit[N] qreg;`, use +Basis treats quantum data explicitly. Declare qubits with `qubit q;` or `qubit[N] qreg;`, use `reset q;` to return a qubit to `|0>`, and `measure q;` to collapse to a `bit`. Applying gates after a measurement raises a runtime error unless you reset first, and `qubit[]` cannot be initialised with literals. @@ -20,7 +20,7 @@ function flip() -> bit { To collect outcomes automatically, annotate qubit variables or fields with `@tracked` (see `annotations-and-tracking.md`). Multi-shot runs come from `@shots(N)` on `main()` or the -`--shots=N` CLI flag (deprecated in v2.0.0), which aggregate tracked values across runs. +`--shots=N` CLI flag, which aggregate tracked values across runs. Each execution produces an OpenQASM file next to your source; add `--emit-qasm` to print it as well. diff --git a/docs/runtime.md b/docs/runtime.md index f8f545d..2f7b4ea 100644 --- a/docs/runtime.md +++ b/docs/runtime.md @@ -1,6 +1,6 @@ -# Bloch Runtime Model +# Basis Runtime Model -Bloch executes programs with a tree-walking interpreter and an ideal statevector simulator that +Basis executes programs with a tree-walking interpreter and an ideal statevector simulator that logs OpenQASM 2.0 operations. ## Execution pipeline diff --git a/docs/tooling-and-cli.md b/docs/tooling-and-cli.md index 8e2e810..42c6fee 100644 --- a/docs/tooling-and-cli.md +++ b/docs/tooling-and-cli.md @@ -1,57 +1,18 @@ -# Tooling & CLI - -Run programs with `bloch path/to/file.bloch`. - -## Exit codes - -- **0** — Success (program ran to completion). -- **Non-zero** — Error (lexical, parse, semantic, or runtime). See [Errors & Diagnostics](./diagnostics.md). - -## Common flags - -- `--help` — Show usage and available options. -- `--version` — Print the build string and check for updates. -- `--update` — Download and install the latest release, including the bundled stdlib. -- `--emit-qasm` — Print the emitted OpenQASM log to stdout (in addition to writing `.qasm` beside your source). -- `--shots=N` — Run the program N times and aggregate tracked values. **to be deprecated in v2.0.0;** prefer `@shots(N)` on `main()`. See [Annotations & Tracking](./annotations-and-tracking.md). If both the annotation and this flag are set, the annotation wins and the flag is ignored with a warning. -- `--echo=auto|all|none` — Control echo output. Default `auto` suppresses echo when taking many shots; use `all` for verbose per-shot output, `none` to silence echo. - -Each run writes `.qasm` next to your source file. The `--emit-qasm` flag only controls whether that log is also printed to stdout. - -## Stdlib discovery - -When the CLI resolves imports, it prepares search paths for the stdlib and project libraries: - -- If `BLOCH_STDLIB_PATH` is set, Bloch uses that root first and also checks `1.1.0`/`v1.1.0` - style versioned subdirectories when present. -- Otherwise Bloch checks the platform install location for the stdlib: - - Linux: `$XDG_DATA_HOME/bloch/library` or `~/.local/share/bloch/library` - - macOS: `~/Library/Application Support/Bloch/library` - - Windows: `%LOCALAPPDATA%\Bloch\library` -- Bloch also checks locations beside the installed binary plus local `./library` and `./stdlib` - directories in your current working directory. - -This is why `import bloch.lang.Object;` works immediately after a standard install. - -## Where is `bloch` installed? - -When you install via the install script (Linux/macOS or Windows), the `bloch` binary is placed in a directory on your PATH: - -- **Linux/macOS:** The script prefers `~/.local/bin` if it exists and is writable; otherwise `/usr/local/bin` if writable; otherwise `~/.local/bin` (created if needed). You can override with `INSTALL_DIR`, e.g. `INSTALL_DIR=$HOME/.local/bin`. -- **Windows:** See the PowerShell install script output for the install location. - -To find the binary: `which bloch` (Linux/macOS) or `where bloch` (Windows). - -## Build from source +# CLI ```bash -cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -cmake --build build --parallel -ctest --test-dir build --output-on-failure +basis [options] path/to/program.bloch ``` -The executable is `./build/bin/bloch`. Add it to your PATH or run it with the path when in the repo. +- `--help`: show options. +- `--version`: show the development version and commit. +- `--shots=N`: execute N shots and aggregate `@tracked` values. +- `--echo=auto|all|none`: control echo output. +- `--emit-qasm`: also print the OpenQASM 2 execution trace to stdout. -## Editor support +`@shots(N)` on `main` takes precedence over the CLI shot count. Successful runs +write a `.qasm` trace beside the input file. See [known issues](known-issues.md). -The VS Code extension at [bloch-labs/bloch-vscode](https://github.com/bloch-labs/bloch-vscode) provides syntax highlighting. +The bundled standard library is installed to `/share/basis/library`. +Set `BASIS_STDLIB_PATH` to override its search root. The inherited package name +remains `bloch.lang`; for example, `import bloch.lang.Object;`. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 948033b..1fbbf72 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -17,13 +17,13 @@ If you hit a roadblock, start with the quick checks below and the [Common issues During multi-shot runs, echo defaults to off; pass `--echo=all` if you need output. -If problems persist, reduce shots to simplify debugging, add `echo` statements to inspect state, and pay attention to line/column numbers in error messages. If you have found a bug please raise an issue on GitHub (https://github.com/bloch-labs/bloch) or email hello@bloch-labs.com. +If problems persist, reduce shots to simplify debugging, add `echo` statements to inspect state, and pay attention to line/column numbers in error messages. If you have found a bug please raise an issue on GitHub (https://github.com/akshaysoftware/basis) or email akshay.anu@gmail.com. ## Common issues | Symptom | Cause | Fix | |--------|--------|-----| -| "expected .bloch file" or wrong file run | No file passed or wrong path | Pass the path to your `.bloch` file as the last argument: `bloch path/to/file.bloch`. | +| "expected .bloch file" or wrong file run | No file passed or wrong path | Pass the path to your `.bloch` file as the last argument: `basis path/to/file.bloch`. | | Import / module not found | Import path doesn’t resolve to a file | Ensure the imported module exists at the expected path, package declarations match the import path, and the loader can find it (importing-file directory, configured search paths, or working directory). | | Duplicate definition of main | More than one `main()` in the program | Keep exactly one `main()` across all files that are imported or run. | | Gate-after-measurement error | Gate applied to a qubit that was already measured | Call `reset q;` before applying more gates to `q`, or use a new qubit. See [Quantum Programming](./quantum-programming.md). | @@ -36,4 +36,4 @@ If problems persist, reduce shots to simplify debugging, add `echo` statements t - **Documentation:** Revisit the guides linked from the [docs README](./README.md), especially [Errors & Diagnostics](./diagnostics.md) and the [Language Specification](./language-spec.md). - **Community and support:** See the main repository [README](../README.md) for the project website, community links, and contact (e.g. GitHub Discussions, email). -- **Contributor / implementation details:** For deep dives into the compiler and runtime, see the contributor references in `engineering/reference/`. +- **Contributor / implementation details:** For deep dives into the compiler and runtime, see the contributor references in [architecture guide](architecture.md). diff --git a/docs/types-and-data.md b/docs/types-and-data.md index a549cdf..f8f6360 100644 --- a/docs/types-and-data.md +++ b/docs/types-and-data.md @@ -1,6 +1,6 @@ # Types and Data -Bloch has a compact set of primitives plus arrays and class references. +Basis has a compact set of primitives plus arrays and class references. ## Primitives - `int`, `long`, `float` diff --git a/engineering/adrs/ADR-001-class-system.md b/engineering/adrs/ADR-001-class-system.md deleted file mode 100644 index 20e420e..0000000 --- a/engineering/adrs/ADR-001-class-system.md +++ /dev/null @@ -1,60 +0,0 @@ -# ADR-001: Bloch Class System - -## Owner -Akshay Pal - -## Status -Accepted - -## Delivered In -v1.1.0 - -## Context -This ADR defines the core class system of Bloch including inheritance, dispatch, -construction, visibility, and the relationship to nullability and generics. -Detailed sub-decisions: ADR-002 (null), ADR-003 (generics), ADR-009 (imports). - -## Decision -- Single inheritance only: one optional `extends` clause. -- Every non-static class has implicit root base `Object`. - - `class Animal` is semantically treated as `class Animal extends Object`. -- Root `Object` is provided by stdlib module `bloch.lang.Object`, auto-loaded by - the module loader when available (with a synthetic fallback root for minimal runtime safety). -- Subclass families must remain valid: - - `class Animal { public constructor() -> Animal = default; }` - - `class Dog extends Animal { public constructor() -> Dog { super(); return this; } }` - - `class Cat extends Animal { public constructor() -> Cat { super(); return this; } }` -- Modifiers: `abstract` and `static` at class level. -- Members: `public`, `protected`, `private`; methods may be `virtual`/`override`. -- Construction/destruction: - - Every non-static class must declare at least one constructor. - - `super(...)` only as first constructor statement. - - If `super(...)` is omitted, an accessible zero-arg base constructor is required. - - At most one destructor per class. - - Static classes cannot have instance fields/constructors/destructors. -- Nullability and generics behaviour are governed by ADR-002 and ADR-003. - -## Included -- Single inheritance hierarchy rooted at `Object`. -- Virtual dispatch through an override chain. -- Static and instance members with visibility rules. -- Class-level generics and bounded type parameters. -- Generic diamond inference for constructor calls when assignment target type is known. - -## Explicitly Not Included -- Multiple inheritance. -- Interfaces and traits. -- Method-level generics. -- Wildcard generics (`?`, `? extends`, `? super`). -- Raw types and method-argument-driven generic inference. -- Reflection and runtime annotation processing. - -## Alternatives Considered -- Multiple inheritance or mixins — **rejected** due to increased layout/vtable complexity and ambiguity resolution cost. -- Allow static virtual/override — **rejected** due to dispatch model mismatch; static members have no runtime receiver/vtable. - -## Consequences -- Predictable OO surface for v2.0.0 execution goals. -- A strict "in-scope/out-of-scope" boundary for language users and implementers. -- Consistent semantic/runtime behaviour for implicit `Object`, explicit constructor - requirements, and subtype assignability. diff --git a/engineering/adrs/ADR-002-null-handling.md b/engineering/adrs/ADR-002-null-handling.md deleted file mode 100644 index f6cf62b..0000000 --- a/engineering/adrs/ADR-002-null-handling.md +++ /dev/null @@ -1,29 +0,0 @@ -# ADR-002: Null Handling - -## Owner -Akshay Pal - -## Status -Accepted - -## Delivered In -v1.1.0 - -## Context -Disciplined representation of “no object” while keeping primitives and arrays non-nullable. To be used for explicit comparisons, safe member access, and consistent compile-time/runtime rules. - -## Decision -- Introduce `null` literal. -- Allow `null` only for class references (including generics); disallow for primitives and arrays. -- Permit `==` / `!=` comparisons involving `null`; reject other operators with null. -- Member access on `null` raises `"null reference"` at runtime. -- `destroy null` is accepted as a no-op for defensive cleanup. - -## Alternatives Considered -- Allow null on primitives/arrays — **rejected** due to safety concerns and added checks on every primitive use. -- Implicit coercions involving null — **rejected** due to surprising conversions and loss of explicitness. - -## Consequences -- Arrays and primitives remain non-nullable; class refs are nullable. -- Users must guard member access when a reference may be `null`. -- Consistent semantics across parser/semantic/runtime layers. diff --git a/engineering/adrs/ADR-003-generics.md b/engineering/adrs/ADR-003-generics.md deleted file mode 100644 index 9828f5f..0000000 --- a/engineering/adrs/ADR-003-generics.md +++ /dev/null @@ -1,50 +0,0 @@ -# ADR-003: Class Generics - -## Owner -Akshay Pal - -## Status -Accepted - -## Delivered In -v1.1.0 - -## Context -Bloch requires reusable, type-safe class components (e.g., containers) without runtime type erasure. Requirements include class-level type params, optional bounds, predictable dispatch, compatibility with existing runtime, minimal surface (no method generics/wildcards). - -## Decision -- Generics are class-level only. -- Syntax: - - Declaration: `class Foo` - - Upper bound: `class Foo` - - Use-site: `Foo`, including in `extends`. -- Bounds are upper bounds against class types in the single-inheritance hierarchy. -- Classes without explicit `extends` still participate in the implicit `Object`-rooted hierarchy. -- Runtime uses monomorphisation with specialisation caching. -- Constructor-call diamond inference is supported when the target type is known - (typed declarations, assignments, and returns). -- Nullability unchanged: class references (including generic instantiations) are nullable; - primitives/arrays are not. - -## Explicitly Not Included -- Method-level generics. -- Wildcard generics: `?`, `? extends`, `? super`. -- Declaration-site variance markers. -- Raw types. -- Method-argument-driven generic inference. -- Generic arrays. - -## Alternatives Considered -- Method-level generics — **rejected** due to added parser/runtime complexity for limited gain. -- Wildcards / variance annotations — **rejected** to keep surface small and avoid variance rules in the first iteration. -- Type erasure instead of monomorphisation — **rejected** to preserve runtime type fidelity and dispatch speed. - -## Implementation Notes (v1.1.0) -- Parser and semantic analysis reject wildcard syntax by omission from the grammar. -- Semantic/runtime call and assignment rules use subtype assignability within the - single-inheritance hierarchy. - -## Consequences -- Code size can grow with many specialisations; caching mitigates. -- No generic functions; patterns needing them must wrap in generic classes or overloads. -- Base classes may be generic; specialisations propagate through `extends`. diff --git a/engineering/adrs/ADR-004-shots-annotation.md b/engineering/adrs/ADR-004-shots-annotation.md deleted file mode 100644 index 0f16183..0000000 --- a/engineering/adrs/ADR-004-shots-annotation.md +++ /dev/null @@ -1,28 +0,0 @@ -# ADR-004: @shots Annotation - -## Owner -Akshay Pal - -## Status -Accepted - -## Delivered In -v1.1.0 - -## Context -Bloch supports repeated execution of quantum programs (“shots”). We needed a source-level way to specify the number of shots per program, with precedence rules relative to CLI flags and safe integration with `@quantum` functions. - -## Decision -- Introduce `@shots(N)` annotation on the `main` function only. -- If both CLI `--shots` and `@shots(N)` are present, `@shots` has higher precedence and a warning is emitted about the mismatch. -- `@shots` is rejected on non-`main` functions, and `@quantum` remains disallowed on `main()`. -- Semantic checks enforce placement and validate that `N` is an integer literal. -- Runtime uses the resolved shot count when executing the entry point. - -## Alternatives Considered -- Only CLI flag — **rejected** due to poor portability/reproducibility; keeps config outside source. - -## Consequences -- Users get deterministic shot selection; conflicts produce explicit warnings. -- No per-function or per-block shot overrides—out of scope for simplicity. -- CLI flag to be deprecated in v2.0.0. diff --git a/engineering/adrs/ADR-005-new-v1.1.0-primitives.md b/engineering/adrs/ADR-005-new-v1.1.0-primitives.md deleted file mode 100644 index 3ff5352..0000000 --- a/engineering/adrs/ADR-005-new-v1.1.0-primitives.md +++ /dev/null @@ -1,30 +0,0 @@ -# ADR-005: New Primitives (boolean, long) - -## Owner -Akshay Pal - -## Status -Accepted - -## Delivered In -v1.1.0 - -## Context -- Current primitives: `int`, `float`, `bit`, `char`, `string`, `qubit` (+ arrays). -- There is demand for classical booleans (distinct from measurement `bit`) and wider integer math (signed 64-bit). -- To keep the language lean, we add a primitive only when it adds unique representation/semantics not covered by classes or existing primitives. - -## Decision -- Introduce two new primitives: - 1. `boolean` — classical logic type; literals `true/false`; used for conditionals, logical ops; distinct from `bit` to avoid quantum/classical conflation. - 2. `long` — 64‑bit signed integer. Literal suffix `L` (e.g., `42L`). - -## Alternatives Considered -- Use `bit` as boolean — **rejected** due to conflating quantum measurement with classical logic and creating implicit conversions. -- Rely solely on boxed types — **rejected** due to performance/ergonomics; primitives provide faster arithmetic and leaner storage. - -## Consequences -- Parser/lexer add keywords and literal handling (`true/false`, `L` suffix). -- Semantics add `ValueType::Boolean/Long`; type-checking rules for promotion and operator validity. -- Runtime adds new value kinds and array variants; QASM emission unchanged for classical flow. -- Backward compatibility: existing code unaffected; `bit` semantics unchanged. diff --git a/engineering/adrs/ADR-006-stdlib-boxing.md b/engineering/adrs/ADR-006-stdlib-boxing.md deleted file mode 100644 index 29b2b19..0000000 --- a/engineering/adrs/ADR-006-stdlib-boxing.md +++ /dev/null @@ -1,45 +0,0 @@ -# ADR-006: Stdlib - Boxed Classes for all Primitives - -## Owner -Akshay Pal - -## Status -Proposed - -## Delivered In -Planned for v1.2.0 - -## Context -- This ADR establishes a boxed class for **every primitive** supported by the language. -- We want primitives for performance/representation and boxed references for richer APIs, without adding auto-boxing complexity. -- Quantum primitives (`bit`, `qubit`) are *not* boxed in v1.2.0. - -## Decision -- Create a boxed class per primitive: - - `Boolean` (`boolean`) - - `Integer` (`int`) - - `Long` (`long`) - - `Float` (`float`) - - `Char` (`char`) - - `String` (`string`) - - The `qubit` primitive is deliberately excluded from boxing; quantum state is not safely encapsulated as an object. `bit` remains unboxed; use `Boolean` for classical logic. -- Each boxed class extends `Object` and provides at least: - - Static `of()` - - `override function toPrimitive() -> ` (Object declares `virtual function toPrimitive() -> void` placeholder) - - `equals` override for **value equality** with same-kind boxes - - `toString` override for rendering the contained value -- No automatic boxing/unboxing in v1.2.0; conversions are explicit via constructors/accessors. - -## Alternatives Considered -- Auto-boxing/unboxing — **rejected** to preserve explicit semantics, avoid hidden allocations, and keep runtime simpler for v1.2.0. - -## Consequences -- Stdlib surface expands with boxed classes; documentation and examples updated. -- Runtime unchanged; boxes are ordinary classes. -- Slight verbosity for users (must call `of` / `toPrimitive`) but predictable behaviour. - -## References -- ADR-001 Class System -- ADR-002 Null Handling -- ADR-003 Class Generics -- ADR-005 New Primitives diff --git a/engineering/adrs/ADR-007-stdlib-collections.md b/engineering/adrs/ADR-007-stdlib-collections.md deleted file mode 100644 index e853304..0000000 --- a/engineering/adrs/ADR-007-stdlib-collections.md +++ /dev/null @@ -1,39 +0,0 @@ -# ADR-007: Stdlib Collections Package — Target v1.2.0 - -## Owner -Akshay Pal - -## Status -Proposed - -## Delivered In -Planned for v1.2.0 - -## Context -- With boxing (ADR-006), primitives can be represented as objects. We need a coherent collections surface that operates on reference types (boxed primitives and user classes). -- Goal: provide familiar, minimal, deterministic collections while keeping runtime/simple semantics. - -## Decision -- Introduce the following collections packages: - - `List` - - `Set` - - `Map` - - `Pair` -- Type arguments are reference-oriented (boxed primitives or user classes); with implicit `Object` inheritance, explicit `T extends Object` bounds are unnecessary in API signatures. Primitives themselves are not accepted. -- No concurrent collections, no iterators/generators in v1.2.0; APIs are strict and eager. -- Align with the explicit boxing model and avoid primitive specialisation complexity. -- Keep API surface small yet cover common needs (ordered list, uniqueness set, key/value map, simple pair tuple). - -## Alternatives Considered -- Allow primitives directly — **rejected** because it would require specialisation and inflate surface area. -- Add iterators/generators now — **deferred** to keep v1.2.0 scope tight and implementations simple. - -## Consequences -- Requires stdlib implementations and tests for the four types. -- Examples and docs must show usage with boxed primitives (e.g., `List`) and user classes. -- Runtime unchanged; **all logic is library-level**. - -## References -- ADR-001 Class System -- ADR-003 Class Generics -- ADR-006 Boxed Primitives diff --git a/engineering/adrs/ADR-008-custom-http-lib.md b/engineering/adrs/ADR-008-custom-http-lib.md deleted file mode 100644 index 92d0f67..0000000 --- a/engineering/adrs/ADR-008-custom-http-lib.md +++ /dev/null @@ -1,31 +0,0 @@ -# ADR-008: In-house HTTP Client - -## Owner -Akshay Pal - -## Status -Proposed - -## Delivered In -Planned for v1.2.0 - -## Context -- The updater currently depends on `cpp-httplib` + OpenSSL, which drags transitive deps into all binaries, complicates static builds, and expands the attack surface. -- Upcoming networked tools (package manager, remote execution) need a stable, auditable HTTP surface we control. -- Bloch distributions should keep their footprint small and avoid relying on system OpenSSL availability for plain HTTP. - -## Decision -- Build a first-party HTTP client library `bloch::http` with a minimal synchronous API (GET/POST, headers, timeout) and pluggable transports. -- Default backend: sockets-based HTTP/1.1 client implemented in-tree (no third-party deps). -- Optional backends: TLS via OpenSSL/Schannel; temporary fallback adapter over `cpp-httplib` until the sockets backend reaches parity. -- Expose the library as an installable target (`bloch_http`) and migrate `bloch_update` to consume it once stable. - -## Alternatives Considered -- Keep `cpp-httplib` as the only client — rejected due to dependency and supply-chain exposure. -- Switch to libcurl — rejected for footprint, build complexity, and licensing surface. -- Use platform-native APIs only (WinHTTP, NSURLSession) — rejected for higher divergence and maintenance cost; kept as potential transport plugins. -- Vendor another header-only client (e.g., restclient-cpp) — rejected; still third-party and does not reduce supply-chain risk. - -## Consequences -- Pros: smaller default binary, clearer dependency boundaries, easier static packaging, and testable transport seam. -- Cons/Risks: engineering cost to implement and maintain HTTP + TLS correctly; initial feature set limited to HTTP/1.1 and sync calls; need robust cert validation before defaulting to HTTPS. diff --git a/engineering/adrs/ADR-009-import-system.md b/engineering/adrs/ADR-009-import-system.md deleted file mode 100644 index 58abfed..0000000 --- a/engineering/adrs/ADR-009-import-system.md +++ /dev/null @@ -1,123 +0,0 @@ -# ADR-009: Import and Package System - -## Owner -Akshay Pal - -## Status -Accepted - -## Delivered In -v1.1.0 - -> Note: v1.1.0 includes installed-stdlib discovery via CLI-provided search paths and implicit -> `bloch.lang.Object` bootstrap loading when available. - -## Context -- With the implementation of a class system in Bloch we need to clearly specify an import/package model. -- We want a **Java-style package system** (hierarchical, namespace-based) while **not forcing everything into classes**, closer to C++ where top-level functions and a `main` entry file are idiomatic. -- The import system must: - - Make it easy to organise projects into packages and modules. - - Allow "script-style" entrypoints (e.g. a `main.bloch` file without a package). - - Support a **stdlib** that ships with the language and may later live under a user-local installation root. - - Be future-proof for additional libraries without painting us into a corner. -- Two concrete deployment options for stdlib surfaced: - - A **fixed stdlib directory** such as `~/.local/share/bloch/library` that holds one active stdlib version. - - A **Maven-like repository layout** (e.g. `~/.m2/repository/group/artifact/version/...`) that could host multiple versions and potentially third-party packages. - -## Decision -- **Language model** - - Files may declare an optional **package**: - - `package foo.bar;` - - If omitted, the file is in the **default package**, intended for small programs and entrypoints (`main.bloch` style), similar to C++'s `main.cpp`. - - Files may contain: - - Top-level functions. - - Top-level class declarations (per ADR-001). - - Top-level constant declarations (subject to future ADRs). - - **Imports**: - - `import foo.bar.Baz;` imports a single type or symbol from a package. - - `import foo.bar.*;` imports all symbols from a package (loads all `.bloch` files in that package). - - `import Baz;` imports a symbol from the default package. - - `import bloch.collections.List;` and similar forms are reserved for stdlib and future libraries. - - **Filesystem mapping** - - `import foo.bar.Baz;` resolves to `foo/bar/Baz.bloch`. - - Imported modules must declare `package foo.bar;` (or no `package` for the default package). - - Import resolution is **file-based** in v1.1.x: the compiler maps a fully qualified - import to a concrete `.bloch` path and loads that module before semantic analysis. - Packages are used to validate layout rather than to provide namespaces. - - v1.1.x does **not** provide per-package namespaces; class names must remain unique - across all loaded modules. - -- **Resolution order (v1.1.x)** - - Given an import `import p.q.R;`, resolution walks: - 1. **Directory of the importing file**. - 2. **Configured search paths** (used by tests and embedding). - 3. **Current working directory**. - - For `bloch.*` imports, configured search paths are checked first to avoid project-local - shadowing of stdlib modules. - - The importer stops at the first successful resolution; missing imports are reported as semantic errors. - - For wildcard imports (`import p.q.*;`), the resolver locates the package directory and loads - all `.bloch` files it contains. - -- **Stdlib location (v1.1.0 implementation)** - - Bloch resolves installed stdlib roots by platform: - - Unix-like systems (XDG default): `~/.local/share/bloch/library`. - - Windows (default): `%LOCALAPPDATA%\\Bloch\\library`. - - macOS (default): `~/Library/Application Support/Bloch/library`. - - Override is supported via `BLOCH_STDLIB_PATH`. - - Versioned roots are supported (for example `v1.1.0` and `1.1.0` subdirectories), plus an - unversioned root fallback. - - The loader auto-loads `bloch.lang.Object` before the entry file when that module is available. - - Package names inside the stdlib are stable and decoupled from the physical layout so that a - future ADR can introduce a Maven-like repository without changing user-facing import syntax. - -- **Future extensibility** - - The import resolver is structured around a pluggable **search path**: - - Project roots (always first). - - One or more **library providers** (stdlib is implemented; more providers in future). - - A later ADR may: - - Add a Maven-style multi-version repository for community packages. - - Allow mapping `group:artifact:version` coordinates onto the same import syntax used for the stdlib. - -## Alternatives Considered -- **Alternative 1: Pure Maven-like repository (e.g. `~/.m2`-style) for stdlib** - - Pros: - - Naturally supports multiple versions of the stdlib and third-party packages. - - Aligns with existing tooling mental models (Maven, Gradle, Cargo-style registries). - - Encourages early design for dependency resolution and caching. - - Cons: - - Overkill for v1.1.0, where only a single stdlib version is supported. - - Introduces configuration (coordinates, repositories, version selection) before there is a user-facing package manager. - - Complicates bootstrapping and documentation for new users who "just want the language and its stdlib". - - Outcome: - - **Deferred**; we design the resolver to allow plugging in a Maven-like backend later without changing import syntax. - -- **Alternative 2: Project-only imports (no installed stdlib root)** - - Pros: - - Simplest implementation: only load modules from the current project tree (e.g. `src` + `stdlib` dirs in the repo). - - No need for installation layout or user-local directories. - - Cons: - - Not suitable for real installations and package distributions; every project would need a copy of the stdlib. - - Bloch CLI would not be able to assume a standard stdlib is present on the machine. - - Outcome: - - **Rejected**; we want a standard, shared stdlib installation per Bloch version. - -- **Alternative 3: Require every file to be in a named package** - - Pros: - - Stronger uniformity and clearer namespace hygiene. - - Cons: - - Makes quick scripts and single-file programs awkward. - - Unnecessarily diverges from the C++ ergonomics we want for entrypoints (`main.cpp`-like). - - Outcome: - - **Rejected**; we support a default package for simplicity and C++-like entry files. - -## Consequences -- Projects gain a **clear, documented import and package model** that blends Java-style packages with C++ style entrypoint ergonomics. -- The stdlib is discoverable at a **stable, user-local path** in v1.1.0, while keeping the door - open for future Maven-like dependency resolution without breaking imports. -- Tooling (CLI, editor integrations) can rely on: - - A well-defined mapping from `package` + symbol to files. - - A fixed search order (importing file directory → search paths → working directory), with - `bloch.*` imports preferring configured search paths. -- Future work: - - Additional ADRs to specify a full package manager, Lattice build system, and Maven-like repository layout. - - DES-007 (Import System) defines the concrete compiler/runtime architecture and resolver APIs implementing this ADR. diff --git a/engineering/adrs/ADR-010-lattice-build-system.md b/engineering/adrs/ADR-010-lattice-build-system.md deleted file mode 100644 index 4a03f21..0000000 --- a/engineering/adrs/ADR-010-lattice-build-system.md +++ /dev/null @@ -1,109 +0,0 @@ -# ADR-010: Lattice Build System and Ecosystem Separation - -## Owner -Akshay Pal - -## Status -Proposed - -## Delivered In -Planned for v2.0.0 - -## Context -- Bloch v1.1.x–v1.2.x focuses on: - - Language features. - - A language-level import/package system (ADR-009). - - A versioned stdlib distributed alongside the language (from v1.2.0). -- Build orchestration in 1.x is intentionally simple: - - Users invoke `bloch` directly. - - Users can `import` custom classes into `main.bloch` -- As Bloch moves to **bytecode + JIT** in v2.0.0, there is a clear need for: - - A proper **project model** (modules, targets). - - **Dependency management** (versions, locks, registries). - - **Orchestration** of compiler, runtime, and tooling in a single, cohesive UX. -- We want to keep the core language toolchain focused: - - `blochc`: compiler only. - - `bloch`: runtime/JIT/VM only. - - A **separate build system** will handle orchestration, similar to how `mvn` is separate from `javac/java`, `cargo` is separate to `rustc` and `pip` is separate to `python`. - -## Decision -- **Introduce Lattice as the official Bloch build system** - - Name: **Lattice** (e.g. `lattice build`, `lattice test`). - - Packaged and versioned separately from the Bloch language repo: - - Lattice lives in its own GitHub repository (https://github.com/bloch-labs/lattice). - - Lattice is released and versioned independently of Bloch. - - Lattice is the **official** build system for Bloch: - - Official docs and examples assume Lattice for non-trivial projects. - - The ecosystem is free (and encouraged) to build alternative tools on top of the same compiler/runtime contracts. - -- **Clear separation of responsibilities** - - `blochc` (compiler): - - Parses, typechecks, and compiles Bloch source to IR/bytecode. - - Knows nothing about dependency resolution, remote repositories, or project graphs. - - Exposes a stable CLI and/or library API for Lattice to orchestrate. - - `bloch` (runtime/JIT): - - Executes bytecode, manages runtime libraries, and provides a stable application binary interface (ABI) for compiled artifacts. - - Does not manage dependency resolution or project structure. - - `lattice` (build system): - - Defines the **project model** (modules, targets, test suites). - - Manages **dependencies**: - - The Bloch stdlib (from v1.2.0). - - Future community packages and registries. - - Orchestrates: - - Compilation (`blochc` invocations). - - Running, testing, packaging (calls into `bloch` and other tools). - -- **Implementation language** - - Implementation language is left open in this ADR but should prioritise: - - Strong cross-platform story. - - Single static binary or minimal runtime dependency. - - Great tooling ecosystems for CLI and concurrency. - - Rust and Go are both strong candidates; a later design (DES) can choose concretely. - -- **Timeline and scope** - - v1.1.0: - - Language-level `package` and `import` semantics (ADR-009, DES-007). - - No dedicated build system. - - v1.2.0: - - Stdlib shipped with the language, installed to user-local data directories. - - Compiler knows how to locate the stdlib (via well-defined defaults + environment override). - - Still no Lattice; dependency graph is trivial (stdlib + project). - - v2.0.0: - - Bytecode + JIT architecture in core Bloch. - - **Initial release of Lattice (v1.0.0)** in a separate repository, targeting: - - Single-project builds. - - Integration with stdlib and basic dependency metadata. - - Room to grow into a full-blown package manager over time. - -## Alternatives Considered -- **Alternative 1: No separate build system (compiler does everything)** - - Pros: - - Fewer binaries; simpler mental model for new users. - - Centralised implementation in a single codebase. - - Cons: - - Tight coupling of language evolution with build/dependency concerns. - - Harder for the community to build alternative tools or experiment with different dependency models. - - Risk of `blochc` becoming a monolith that mixes compilation, packaging, testing, and deployment concerns. - - Outcome: - - **Rejected**; we explicitly separate compiler/runtime and build system responsibilities. - -- **Alternative 2: Delay build system beyond v2.0.0** - - Pros: - - More time to observe user needs and JIT behaviour. - - Avoid taking on build/dependency complexity too early. - - Cons: - - Users would lack a first-class, idiomatic way to build and test Bloch projects using the new bytecode model. - - Third-party tools might fill the gap in fragmented ways, creating migration pain later. - - Outcome: - - **Rejected**; v2.0.0 is the right inflection point to deliver an official, cohesive story. - -## Consequences -- Bloch’s core toolchain remains **focused**: - - Compiler and runtime are small, well-defined components with stable CLIs. -- The community gets: - - A clear, official build tool (`lattice`) for day-to-day development once v2.0.0 lands. - - The freedom to write alternative build systems without being blocked by monolithic compiler design. -- Documentation and onboarding flows: - - 1.x docs emphasise direct `bloch` usage. - - 2.x docs emphasise `lattice` for project-level builds, while still documenting direct compiler/runtime usage where needed. - diff --git a/engineering/designs/DES-001-class-system.md b/engineering/designs/DES-001-class-system.md deleted file mode 100644 index 4c7c94a..0000000 --- a/engineering/designs/DES-001-class-system.md +++ /dev/null @@ -1,176 +0,0 @@ -# DES-001: Class System Architecture (C++) - -## Scope -* ADR-001 -* ADR-002 -* ADR-003 -* ADR-009 - -## Design Goals -- Keep Bloch OO behaviour predictable for the v2.0.0 execution model. -- Preserve a strict single-inheritance tree rooted at `Object`. -- Keep generic surface intentionally small and explicit. -- Make stdlib `bloch.lang.Object` available out-of-the-box after install. - -## Included vs Excluded -### Included -- Single inheritance. -- Root `Object` for all non-static classes. -- Virtual dispatch (`virtual` + `override`). -- Class-level generics with optional upper bounds. -- Visibility modifiers (`public`, `protected`, `private`). - -### Excluded -- Multiple inheritance. -- Interfaces/traits. -- Method-level generics. -- Wildcard generics (`?`, `? extends`, `? super`). -- Raw types and method-argument-driven generic inference. - -## High-Level Flow -
- -```mermaid -flowchart TD - Tokens -->|parse| AST[AST: Program, ClassDeclaration] - AST -->|class registry| Sem[Semantic passes] - Sem -->|validated types| IR[Runtime metadata: RuntimeClass] - IR -->|instantiation| RT[Runtime execution] - RT -->|monomorphise| Cache[Specialisation cache] -``` - -Figure: End-to-end class pipeline - -
- -## Object Root Model -```bloch -class Animal { public constructor() -> Animal = default; } -class Dog extends Animal { public constructor() -> Dog { super(); return this; } } -class Cat extends Animal { public constructor() -> Cat { super(); return this; } } -``` - -Semantic desugaring target: -- `Animal` becomes `Animal extends Object`. -- Every non-static class must declare at least one constructor. -- `Dog` and `Cat` remain direct subclasses of `Animal`. - -Required runtime consequence: -- Constructor chains always terminate at `Object`. -- Every class reference is assignable to `Object`. - -## Compilation (Lexer/Parser/AST) -- Files: `src/bloch/compiler/parser/parser.{hpp,cpp}`, `src/bloch/compiler/ast/ast.hpp`. -- `ClassDeclaration`: `typeParameters`, `baseType` (generic-aware), legacy `baseName`. -- `NamedType`: `nameParts`, `typeArguments`. -- Flow: modifiers → name → optional `<...>` → optional `extends` (`parseType`) → body members. -- Parser correctly enforces one `extends` clause (single inheritance). -- Generic grammar intentionally excludes wildcard tokens. - -## Semantic Analysis -- Files: `src/bloch/compiler/semantics/semantic_analyser.{hpp,cpp}`. -- Core structs: - - `TypeInfo { value, className, typeArgs, isTypeParam }` - - `ClassInfo { name, base, typeParams, fields, methods, constructors, abstractMethods, ... }` -- Registry responsibilities: - - Collect classes and bounds. - - Validate single-inheritance chains and override legality. - - Enforce static-context and final-field rules. -- Type resolution: `typeFromAst`, `validateTypeApplication`, substitution helpers (`substituteTypeParams`, `substituteMany`). -- Inheritance/overrides target: - - Omitted `extends` maps to `Object`. - - `override` must match virtual base signature. - - Static methods cannot be `virtual`/`override`. - - Bodyless `virtual` makes class abstract. -- Constructor target: - - `super(...)` must be first when present. - - Omitted `super(...)` requires an accessible zero-arg base constructor. -- Generics target: - - Diamond inference for `new T<>()` is applied only when target type is known. - - No raw types or wildcard syntax. -- Null rules: only class refs nullable; null only in `==/!=`; member access on null rejected. -- Generics: class-level only; bounds enforced; no wildcard support by design. -- Overloading: per-name buckets; duplicate signatures rejected; resolution via - assignability-based cost selection (`findMethodInHierarchy` + conversion-cost matching) - so the most specific applicable overload is selected. - -## Runtime Architecture -- Files: `src/bloch/runtime/runtime_evaluator.{hpp,cpp}`. -- Data: - - `RuntimeClass` (layout, vtable, methods, constructors, type args) - - `RuntimeTypeInfo` (kind, className, typeArgs) -- Build: - - Non-generic classes materialised eagerly. - - Generic templates stored and instantiated lazily. - - Base layout/vtable copied before derived members. -- Monomorphisation: - - `instantiateGeneric` substitutes type parameters (including base type args). - - Concrete specialisations cached by a stable key. -- Dispatch: - - One vtable chain per class hierarchy. - - Overrides replace inherited slots. - - Overloads remain in per-name buckets. -- Null handling: null has `objectValue == nullptr`; member access throws `"null reference"`; `destroy null` is a no-op. - -## Object Class + Stdlib Implementation -### Source Layout (repo) -- `library/bloch/lang/Object.bloch` -- Package declaration inside file: `package bloch.lang;` -- `bloch.lang` is a reserved stdlib package. - -### Minimum Object API -- `public constructor() -> Object = default;` -- `public virtual function equals(Object other) -> boolean` (default: reference equality) -- `public virtual function toString() -> string` - -### Installation Layout (user machine) -- Linux/XDG default: `~/.local/share/bloch/library//` -- macOS default: `~/Library/Application Support/Bloch/library//` -- Windows default: `%LOCALAPPDATA%\\Bloch\\library\\\\` -- Environment override for tooling/CI: `BLOCH_STDLIB_PATH` - -Note: -- Use `.local/share` (XDG), not `.local/shared`. - -### Resolution Requirements -- After Bloch installation, stdlib must work without extra flags. -- Loader behaviour: - - Default imports: importing file directory → configured search paths → current working directory. - - `bloch.*` imports (including implicit `bloch.lang.Object` bootstrap): configured - search paths first, then importing directory/current working directory. -- CLI provides stdlib search paths by default from: - - User data directories (`~/.local/share/bloch/library`, platform equivalents), - - Versioned stdlib subdirectories, - - The executable-adjacent install tree (`../share/bloch/library`), - - `BLOCH_STDLIB_PATH` override. -- Result: `bloch.lang.*` resolves to installed stdlib by default and project-local - shadowing is prevented in the standard CLI path. - -## Edge Cases That Must Be Covered -- Inheritance cycle detection (`A extends B`, `B extends A`). -- `super(...)` usage restricted to first constructor statement. -- Implicit `super()` must resolve to a unique, accessible zero-arg base constructor. -- `super`/`this` forbidden in static context. -- Override mismatch errors: missing base, non-virtual base, signature drift. -- Generic bound enforcement across inheritance chains. -- No wildcard generics accepted anywhere in parser or semantic passes. -- Root behaviour: - - `class Animal { public constructor() -> Animal = default; }` is valid and inherits `Object`. - - `extends Object` is valid and equivalent to omission. - - `super()` from direct `Object` subclasses is legal and no-op beyond `Object` ctor. - -## Testing Requirements -- Parser tests for no-wildcard generic rejection. -- Semantic tests: - - `class Animal { public constructor() -> Animal = default; }` accepted. - - `class A extends Object { public constructor() -> A { super(); return this; } }` accepted without user-defined `Object`. - - `Animal a = new Dog();` accepted. -- Runtime tests: - - `Dog`/`Cat` hierarchy dispatch still works under implicit `Object`. - - Constructor chain ends at `Object`. - - `bloch.lang.Object` resolves from installed stdlib without manual flags. - -## Compatibility -- Single inheritance remains the only inheritance model. -- Generics remain class-level and intentionally non-variant. -- Interfaces and method generics remain future work. diff --git a/engineering/designs/DES-002-shots.md b/engineering/designs/DES-002-shots.md deleted file mode 100644 index 2b870b0..0000000 --- a/engineering/designs/DES-002-shots.md +++ /dev/null @@ -1,28 +0,0 @@ -# DES-002: @shots Annotation Design - -## Scope -* ADR-004 - -## High Level Flow -- Parser reads `@shots(N)` on `main` → Semantics validates placement/value → Runtime resolves shot count vs CLI → Execution uses resolved count. - -## Compilation (Lexer/Parser/AST) -- `@shots(N)` parsed as function annotation; allowed on `main` only. -- `N` must be an integer literal; stored on annotation node. - -## Semantic Analysis -- Reject `@shots` on non-`main` or multiple occurrences. -- Validate `N` is integer literal. -- Ensure `@quantum` is rejected on `main()` even when `@shots` is present. - -## Runtime Architecture -- Shot resolution order: annotation > CLI `--shots` > default. -- When both CLI and annotation differ, emit warning and use annotation value. -- Execution loops over resolved shot count, aggregates tracked values, and respects echo suppression defaults. - -## Testing -- Semantic tests: placement, multiplicity, literal checks, invalid types. -- Integration: annotation alone; CLI alone; conflicts produce warning and use annotation. - -## Compatibility -- Backward-compatible: CLI still works; annotation is preferred when present. No impact on non-quantum programs beyond shot handling. diff --git a/engineering/designs/DES-003-primitives.md b/engineering/designs/DES-003-primitives.md deleted file mode 100644 index 1312063..0000000 --- a/engineering/designs/DES-003-primitives.md +++ /dev/null @@ -1,33 +0,0 @@ -# DES-003: New Primitives (boolean, long) - -## Scope -* ADR-005 - -## High Level Flow -- Lexer adds keywords/literal suffixes → Parser recognises `boolean`/`long` primitives and `L` suffix → Semantics enforces type rules/promotions → Runtime adds value kinds/ops/printing. - -## Compilation (Lexer/Parser/AST) -- Lexer: keywords `boolean`, `true`, `false`; literal suffix `L` for long. -- Parser: `PrimitiveType` accepts `boolean` and `long`; literals tagged with widened kind. -- AST touchpoints: `token.hpp`, `lexer.cpp`, `parser.cpp`. - -## Semantic Analysis -- `ValueType` adds `Boolean`, `Long`. -- Promotions: `int + long -> long`; `long` with `float -> float`; `boolean` only in logical ops/conditions. -- Control flow: `boolean` (and `bit` for backward compatibility) allowed in conditionals; consider future lint against `bit` in classical predicates. -- Nullability: unchanged; primitives remain non-nullable. - -## Runtime Architecture -- `Value::Type` adds `Boolean`, `Long` plus array variants (`BooleanArray`, `LongArray` where needed). -- Storage: `Boolean` compact; `Long` 64-bit. -- Ops: arithmetic/bitwise for `long` mirror `int` but 64-bit; logical ops on `boolean`. -- Echo/QASM: `boolean` prints `true/false`. - -## Testing -- Parser: literals (`true/false`, `123L`), type parsing, mixed expressions. -- Semantics: invalid mixes (`boolean + int`), promotions, control-flow acceptance. -- Runtime: `long` edge cases (overflow behaviour), boolean logic. -- Integration: example programs using new primitives and boxed counterparts. - -## Compatibility -- Existing code unaffected; `bit` semantics unchanged. No auto-widening except via explicit long operations; literals without `L` stay `int`. diff --git a/engineering/designs/DES-004-boxing.md b/engineering/designs/DES-004-boxing.md deleted file mode 100644 index 98bd769..0000000 --- a/engineering/designs/DES-004-boxing.md +++ /dev/null @@ -1,106 +0,0 @@ -# DES-004: Stdlib - Boxing - -## Scope -* ADR-006 - -## High Level Flow -- Parser unchanged → Semantics unchanged → Runtime unchanged → Stdlib provides boxed classes with explicit constructors/accessors. - -## Compilation (Lexer/Parser/AST) -- No compiler changes. - -## Semantic Analysis -- No semantic analysis changes. - -## Runtime Architecture -- No runtime changes. - -## Stdlib Classes & APIs -- **Object** - - ctor: `Object()` - - virtual `equals(Object) -> boolean` (reference equality default) - - virtual `toPrimitive() -> void` placeholder - -- **Boolean** - - `of(boolean) -> Boolean` - - `toPrimitive() -> boolean` - - `equals(Object) -> boolean` (value-based) - - `toString() -> string` ("true"/"false") - - `and(Boolean) -> Boolean` - - `or(Boolean) -> Boolean` - - `xor(Boolean) -> Boolean` - - `not() -> Boolean` - - `static parse(string) -> Boolean` - -- **Integer** - - `of(int) -> Integer` - - `toPrimitive() -> int` - - `equals(Object) -> boolean` (value-based) - - `toString() -> string` - - `toHexString() -> string` - - `toBinaryString() -> string` - - `abs() -> Integer` - - `negate() -> Integer` - - `static parse(string) -> Integer` - - `static min(Integer, Integer) -> Integer` - - `static max(Integer, Integer) -> Integer` - -- **Long** - - `of(long) -> Long` - - `toPrimitive() -> long` - - `equals(Object) -> boolean` - - `toString() -> string` - - `toHexString() -> string` - - `toBinaryString() -> string` - - `abs() -> Long` - - `negate() -> Long` - - `static parse(string) -> Long` - - `static min(Long, Long) -> Long` - - `static max(Long, Long) -> Long` - -- **Float** - - `of(float) -> Float` - - `toPrimitive() -> float` - - `equals(Object) -> boolean` - - `toString() -> string` - - `abs() -> Float` - - `negate() -> Float` - - `floor() -> Float` - - `ceil() -> Float` - - `round() -> Integer` - - `static parse(string) -> Float` - - `static min(Float, Float) -> Float` - - `static max(Float, Float) -> Float` - -- **Char** - - `of(char) -> Char` - - `toPrimitive() -> char` - - `equals(Object) -> boolean` - - `toString() -> string` (single-character) - - `isDigit() -> boolean` - - `isLetter() -> boolean` - - `isWhitespace() -> boolean` - - `toUpper() -> Char` - - `toLower() -> Char` - -- **String** - - `of(string) -> String` - - `toPrimitive() -> string` - - `equals(Object) -> boolean` (value-based) - - `toString() -> string` - - `length() -> int` - - `isEmpty() -> boolean` - - `concat(String) -> String` - - `substring(int start, int end) -> String` - - `toUpper() -> String` - - `toLower() -> String` - - `trim() -> String` - - `startsWith(String) -> boolean` - - `endsWith(String) -> boolean` - - `static join(String sep, String[] parts) -> String` - -## Testing -- Unit tests per class. - -## Compatibility -- Explicit boxing/unboxing; no auto-boxing. `bit`/`qubit` remain unboxed. Boxes use standard class rules. diff --git a/engineering/designs/DES-005-stdlib-collections.md b/engineering/designs/DES-005-stdlib-collections.md deleted file mode 100644 index b02342d..0000000 --- a/engineering/designs/DES-005-stdlib-collections.md +++ /dev/null @@ -1,63 +0,0 @@ -# DES-005: Stdlib Collections Package - -## Scope -* ADR-007 - -## High Level Flow -- Collections are plain classes; no compiler/runtime changes. Factories and methods are implemented within stdlib code. - -## Compilation (Lexer/Parser/AST) -- No compilation changes. - -## Semantic Analysis -- No semantic analysis changes. - -## Runtime Architecture -- No runtime changes. - -## Stdlib Classes & APIs - -- **List** - - `static of(T v1, T v2?, ...) -> List` - - `add(T) -> void` - - `get(int index) -> T` - - `contains(T) -> boolean` - - `clear() -> void` - - `size() -> int` - - `isEmpty() -> boolean`. - - Semantics: singly linked backing is acceptable; index out-of-range throws runtime error. - -- **Set** - - `static of(T v1, ...) -> Set` - - `add(T) -> boolean` (true if inserted) - - `remove(T) -> boolean` - - `contains(T) -> boolean` - - `size() -> int` - - `isEmpty() -> boolean` - - `clear() -> void`. - - Semantics: uniqueness by `equals`; initial implementation may be linear or hashed but deterministic. - -- **Map** - - `static of(K k1, V v1, K k2, V v2, ...) -> Map` - - `put(K,V) -> void` - - `get(K) -> V` - - `containsKey(K) -> boolean` - - `remove(K) -> V` - - `size() -> int` - - `isEmpty() -> boolean` - - `clear() -> void`. - - Semantics: key equality via `equals`; linear map acceptable for v1.2.0. - -- **Pair** - - `static of(A,B) -> Pair` - - `first() -> A` - - `second() -> B` - - `equals(Object) -> boolean` (value-based) - - `toString() -> string` in the form `(a,b)`. - -## Testing -- Unit tests per class: creation, core ops, size/emptiness, error cases (out of range/missing key), equality behaviour. -- Integration: examples using boxed primitives and user classes (`List`, `Set`, `Map`, `Pair`). - -## Compatibility -- Reference-only intent: APIs are designed for class references (including boxed primitives) and rely on `Object`-level behaviour via implicit inheritance. No iterators/generators; all operations are eager and deterministic. diff --git a/engineering/designs/DES-006-custom-http-lib.md b/engineering/designs/DES-006-custom-http-lib.md deleted file mode 100644 index 5b36770..0000000 --- a/engineering/designs/DES-006-custom-http-lib.md +++ /dev/null @@ -1,32 +0,0 @@ -# DES-006: In-house HTTP Client - -## Scope -* ADR-008 - -## High Level Flow -`Client` → `Transport` (strategy) → `Socket/TLS adapter` → network → response → `Response` object. - -## Compilation (Lexer/Parser/AST) -- No change. - -## Semantic Analysis -- No change. - -## Runtime Architecture -- Target: new CMake target `bloch_http` builds from `src/bloch/http/*`. -- Facade: `bloch::http::Client` with `get`/`post`. -- Data types: `Request { method, url, headers, body, timeout_ms }`, `Response { status, headers, body, ok() }`. -- Transport interface (strategy): `Transport::execute(Request) -> Response`. -- Implementations: - - `SocketsTransport` (default): blocking POSIX/WinSock HTTP/1.1, keep-alive optional. - - `OpenSSLTransport` (opt-in): wraps sockets with TLS; validates host + cert store. -- Config: backend selected at build; runtime selection possible via an env var/flag if needed later. - -## Testing -- Unit tests: transport-independent tests using a loopback harness (send/echo, status codes, headers, timeouts). -- Integration (optional/CI-guarded): hits known httpbin endpoints for real network coverage. -- TLS tests: pinned cert local server to validate hostname verification. - -## Compatibility -- Platforms: POSIX + WinSock for sockets backend; TLS via OpenSSL initially, Schannel/Darwin Security frameworks considered later. -- HTTP/1.1 only; no proxy or HTTP/2 support initially. Streaming/async deferred to later revisions. diff --git a/engineering/designs/DES-007-import-system.md b/engineering/designs/DES-007-import-system.md deleted file mode 100644 index e4be7c5..0000000 --- a/engineering/designs/DES-007-import-system.md +++ /dev/null @@ -1,145 +0,0 @@ -# DES-007: Import and Package System - -## Scope -* ADR-001 -* ADR-009 - -## High Level Flow -- The import system wires into the existing compilation pipeline by: - - Recording optional `package` declarations and `import` lists per file during parsing. - - Loading imported modules **before semantic analysis** via `ModuleLoader`. - - Validating that imported modules declare the expected `package`. - - Exposing the merged program to semantic analysis and the runtime. - -Conceptual flow: -- Source file → Lexer → Parser (package/imports + declarations) → Module loader (load imports) → - Semantic analyser → Runtime (no additional import logic; works over merged AST). - -## Compilation (Lexer/Parser/AST) -- **Files** - - `src/bloch/compiler/lexer/lexer.{hpp,cpp}` - - `src/bloch/compiler/parser/parser.{hpp,cpp}` - - `src/bloch/compiler/ast/ast.hpp` - - `src/bloch/compiler/import/module_loader.{hpp,cpp}` - -- **Lexer** - - Ensure the following tokens are recognised as keywords: - - `package` - - `import` - - No additional lexing complexity is required; `.` is already a token used for member access and qualified names. - -- **AST** - - Extend the **file-level AST** node (`Program`) to include: - - `std::unique_ptr packageDecl;` - - `std::vector> imports;` - - Structures: - - `PackageDeclaration { std::vector nameParts; /* e.g. ["foo","bar"] */ }` - - `ImportDeclaration {` - - ` std::vector packageParts; // e.g. ["foo","bar"]` - - ` std::optional symbol; // e.g. "Baz" if single-type import` - - ` bool isWildcard; // true for import foo.bar.*;` - - `}` - - Reuse `NamedType` from the class system design for types referenced in imports where appropriate. - -- **Parser** - - At the start of each file: - - Optionally parse a `package` declaration: - - Grammar (simplified): `PackageDecl := "package" Identifier ( "." Identifier )* ";"`. - - At most one per file; duplicates are an error. - - Parse zero or more `import` declarations: - - Grammar (simplified): - - `ImportDecl := "import" QualifiedName ";" | "import" QualifiedName "." "*" ";"`. - - `QualifiedName := Identifier ( "." Identifier )*`. - - Disallow `import` after top-level declarations (for v1.1.0) to keep the file structure simple. - - Attach the parsed `packageDecl` and `imports` to the file-level AST node. - - For entrypoint-like files that omit a package (default package), `packageDecl` is left empty. - - The `ModuleLoader` enforces that **imported modules** declare a `package` matching the - import path (`foo.bar` → `foo/bar`), while entry files may remain in the default package. - -## Semantic Analysis -- **Files** - - `src/bloch/compiler/semantics/semantic_analyser.{hpp,cpp}` - - `src/bloch/compiler/import/module_loader.{hpp,cpp}` - -- **Current behaviour (v1.1.x)** - - `ModuleLoader` resolves and loads imports before semantic analysis. - - The semantic analyser operates on a **merged AST** and does not use `ImportDeclaration` - for name resolution. - - Names are effectively global; duplicate class names across packages are reported as errors. - - Package declarations are kept for diagnostics and to validate filesystem layout. - -- **Planned behaviour (future ADR/DES)** - - Introduce a package-level symbol table and import scoping rules - (explicit vs wildcard, local vs imported). - -## Runtime Architecture -- **Files** - - `src/bloch/runtime/runtime_evaluator.{hpp,cpp}` - - `src/bloch/compiler/import/module_loader.{hpp,cpp}` - -- **Runtime impact** - - The runtime (e.g. `RuntimeClass`, `RuntimeTypeInfo`) does **not** need to understand packages or imports directly. - - Once semantic analysis has completed, the runtime executes the merged program; no - additional import logic is required at runtime. - -- **ModuleLoader responsibilities** - - Resolve imports to on-disk paths using the package mapping (`foo.bar` → `foo/bar`). - - Search order for imports: - 1. Directory of the importing file. - 2. Configured search paths (used by tests/embedding). - 3. Current working directory. - - For `bloch.*` imports, configured search paths are checked first to avoid project shadowing - of installed stdlib modules. - - For `import foo.bar.Baz;` load `foo/bar/Baz.bloch`. - - For `import foo.bar.*;` load all `.bloch` files in `foo/bar/`. - - Support default-package symbol imports (`import Foo;`). - - Auto-load `bloch.lang.Object` before the entry module when available. - - Validate that each imported module declares `package foo.bar;` (or no `package` for the default package). - - Detect import cycles, cache loaded modules, and enforce a single `main()` across the graph. - -- **Stdlib layout (implemented in v1.1.0)** - - CLI supplies platform-aware stdlib roots (plus `BLOCH_STDLIB_PATH` override) to - `ModuleLoader`. - - Versioned stdlib directories are supported (`vX.Y.Z`, `X.Y.Z`) with root fallback. - - The import syntax remains stable and does not expose physical directory layout. - -## Testing -- **Unit tests (compiler)** - - Parser tests: - - Files with and without `package` declarations. - - Multiple `import` forms, wildcard imports, and order of declarations. - - Rejection of multiple package declarations per file. - - Semantic tests: - - Duplicate class names across imports are reported as errors. - - Package declarations are optional on entry files (default package). - -- **Unit tests (ModuleLoader/runtime import coverage)** - - Pure C++ tests for the module loader logic with a fake filesystem layout: - - Resolution from the importing file's directory. - - Resolution from configured search paths. - - `bloch.*` precedence to protect installed stdlib modules from project shadowing. - - Implicit `bloch.lang.Object` bootstrap when available. - - Wildcard imports that load all `.bloch` files in a package directory. - - Package mismatch errors when an imported module declares the wrong package. - - Import cycle detection and multiple-main errors. - -- **Integration tests** - - Example programs that: - - Use `package` and `import` to structure code over multiple files. - - Omit `package` in a `main.bloch`-style entrypoint and still import from packaged code. - - Ensure diagnostics are clear when imports fail (e.g. missing module, package mismatch). - -## Compatibility -- **Backwards compatibility** - - Existing single-file programs without `package` declarations remain valid as default-package files. - - Projects that previously relied on path-based multi-file loading are normalised into the - package/import model; import syntax is additive. - - The in-repo `stdlib/` directory can be added via search paths during development. - -- **Forward compatibility** - - The import system is intentionally **agnostic** to the underlying library distribution mechanism: - - Today: local project paths plus installed stdlib roots in v1.1.0. - - Future: Maven-like repository and package manager that expose the same logical packages to the compiler. - - By treating `ModuleLoader` and a small "library provider" abstraction as the only components aware of on-disk layout, we can: - - Swap in a `.m2`-like structure without changing language syntax. - - Introduce library versioning and third-party packages under new ADRs, while preserving the v1.1.0 import semantics. diff --git a/engineering/designs/DES-008-lattice-build-system.md b/engineering/designs/DES-008-lattice-build-system.md deleted file mode 100644 index 5bb6ef2..0000000 --- a/engineering/designs/DES-008-lattice-build-system.md +++ /dev/null @@ -1,93 +0,0 @@ -# DES-008: Lattice Build System – High-Level Design - -## Scope -* ADR-010 (Lattice Build System) -* ADR-009 (Import and Package System) - -## High Level Flow -- Lattice orchestrates Bloch compilation and execution without embedding compiler/runtime logic. -- Conceptual flows: - - `lattice build`: - - Read project descriptor → resolve dependencies → compute build graph → invoke `blochc` for each module → produce compiled artifacts (e.g. bytecode bundles). - - `lattice run`: - - Ensure build is up to date → call `bloch` with the correct entrypoint and artifact set. - - `lattice test`: - - Discover tests (per project config conventions) → build test targets → run via `bloch` with appropriate flags. - -## Compilation (Compiler CLI Contract) -- Lattice treats the Bloch compiler as an external tool with a **stable CLI**: - - Example shape (illustrative only; exact flags to be defined in a later compiler ADR/DES): - - `blochc --source-root src --out build/main.bbc --stdlib-path --target bytecode` - - Required capabilities: - - Multiple source roots (project code, generated code). - - Configurable output directory / artifact name. - - Overridable stdlib path (e.g. via `--stdlib-path`), consistent with ADR-009/DES-007. - - Deterministic exits and diagnostics (machine-readable output is a plus). -- In v1.1.x–v1.2.x: - - These CLI contracts are introduced and stabilised even before Lattice ships. - - This allows users to write ad-hoc scripts and CI integrations that will later be smoothly migrated into Lattice. - -## Semantic Analysis -- Lattice does **not** perform semantic analysis of Bloch code itself. -- It: - - Coordinates **when** `blochc` is run and on which inputs. - - Caches compilation results at the module/target level based on: - - Source file hashes. - - Compiler version and flags. - - Dependency graph changes. -- All language semantics (import resolution, type checking, generics, etc.) remain within the Bloch compiler as described in ADR-001/009 and related DES docs. - -## Runtime Architecture -- Lattice treats the Bloch runtime (`bloch`) as another external tool: - - Example shape: - - `bloch --run build/main.bbc --entry main.bloch.MainClass` - - Lattice responsibilities: - - Choosing which compiled artifacts to pass to `bloch`. - - Managing runtime configuration (environment variables, flags) in a reproducible, declarative way. - - Coordinating test execution and integration with external tools (coverage, profilers). -- The runtime itself: - - Implements bytecode execution and JIT (v2.0.0+). - - Exposes stable entrypoints for Lattice to call, but remains independent of project/dependency semantics. - -## Dependency Management -- High-level goals (to be elaborated in future ADRs/DESs): - - Model dependencies at the package/module level, aligned with the Bloch package/import system. - - Support: - - The Bloch stdlib (from v1.2.0). - - Future community packages hosted in a Maven-like or registry-based layout. - - Provide: - - Lockfiles for reproducible builds. - - Caching of downloaded/compiled artifacts. -- Lattice will: - - Own the mapping from logical dependencies (e.g. `group:artifact:version`) to on-disk artifacts that `blochc`/`bloch` consume. - - Use the same stdlib resolution conventions as the compiler: - - User-local data directories (`~/.local/share`, `%LOCALAPPDATA%`, etc.). - - Environment overrides for non-standard installations and CI. - -## Testing -- Lattice’s own test strategy: - - **Unit tests**: - - Project descriptor parsing and validation. - - Dependency resolution (including conflicting versions and overrides). - - Build graph construction and caching behaviour. - - **Integration tests**: - - End-to-end `lattice build/run/test` flows against small Bloch projects. - - Cross-platform tests for stdlib resolution and user-local paths. - - **Contract tests with `blochc` and `bloch`**: - - Verify Lattice is compatible across compiler/runtime versions within a supported range. - - Ensure error propagation and diagnostics are surfaced clearly to users. - -## Compatibility -- **With v1.x** - - Lattice is **not** required for v1.x, but: - - Compiler CLI contracts introduced in late 1.x are designed so that adoption of Lattice in 2.0.0 does not break existing scripts. - - Users can continue to call `blochc`/`bloch` directly even after Lattice is introduced. -- **With v2.x and beyond** - - Lattice is the recommended way to: - - Manage dependencies. - - Orchestrate builds and tests. - - Integrate with registries and package ecosystems. - - The language remains usable without Lattice for: - - Small, single-file experiments. - - Low-level or embedded scenarios where a build system is undesirable. - diff --git a/engineering/reference/README.md b/engineering/reference/README.md deleted file mode 100644 index a1045ab..0000000 --- a/engineering/reference/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Contributor Documentation - -This folder contains contributor-facing documentation. Start with the overview and contribution -workflow, then dive into component references as needed. - -## Start here -- [How to Contribute](./how-to-contribute.md) -- [Codebase Overview](./codebase-overview.md) - -## Reference by subsystem -- [Architecture](./architecture.md) -- [Lexer](./lexer.md) -- [Parser](./parser.md) -- [AST](./ast.md) -- [Semantics](./semantics.md) -- [Module Loader](./module-loader.md) -- [Runtime Evaluator](./runtime-evaluator.md) -- [QASM Simulator](./qasm-simulator.md) -- [QASM Mapping](./qasm-mapping.md) -- [CLI](./cli.md) -- [Update Manager](./update-manager.md) -- [Testing](./testing.md) -- [Coding Standards](./coding-standards.md) -- [Support & Errors](./support-and-errors.md) -- [Built-ins](./builtins.md) - -## Design history -- ADRs: `engineering/adrs/` -- Design docs: `engineering/designs/` diff --git a/engineering/reference/architecture.md b/engineering/reference/architecture.md deleted file mode 100644 index 7af890e..0000000 --- a/engineering/reference/architecture.md +++ /dev/null @@ -1,18 +0,0 @@ -# Architecture - -The Bloch toolchain flows from the CLI down to the simulator in a straight line. `src/main.cpp` -is a thin wrapper that delegates to `src/bloch/cli/cli.cpp`, where flags are parsed, update checks -run, and stdlib search paths are prepared. The module loader resolves imports relative to the -caller and optional search paths, auto-loads `bloch.lang.Object` when available, and merges -everything into a single program while enforcing that only one `main()` exists. The lexer, parser, -and AST builder convert source into a typed tree with source locations; the semantic analyser then -checks names, types, annotations, visibility, inheritance rules, and built-in gate signatures. -Only if semantics succeed does the runtime step in: `RuntimeEvaluator` walks the AST, constructs -runtime class metadata, executes classical code, and delegates quantum operations to the -`QasmSimulator`. The simulator maintains the statevector, prevents gates on measured qubits, and -logs OpenQASM that is written beside the source file after execution. Tracked variables aggregate -measurement outcomes across shots when requested, and errors anywhere in the chain surface as -`BlochError` with line/column when available. Extending the system means threading changes through -the same pipeline: new syntax or gates begin in the front-end, pick up validation in semantics, -and finish with runtime behaviour and simulator support, while tests in `tests/` keep the flow -stable. diff --git a/engineering/reference/ast.md b/engineering/reference/ast.md deleted file mode 100644 index 6e38668..0000000 --- a/engineering/reference/ast.md +++ /dev/null @@ -1,28 +0,0 @@ -# AST -Source: `src/bloch/compiler/ast/ast.hpp` - -Inputs: -- Constructed by the parser from token streams - -Outputs: -- Typed node tree consumed by semantics and runtime - -Behaviour: -The AST layer is a catalogue of node structs covering expressions, statements, types, annotations, classes, functions, and the overall program. Each node stores its line and column, and every type supports `accept` so later passes can traverse uniformly via `ASTVisitor`. - -Invariants/Guarantees: -- Ownership via `std::unique_ptr` for child nodes to avoid leaks and clarify lifetimes. -- Visitor must implement all node types; adding nodes requires extending the interface. - -Edge Cases/Errors: -- None at the AST level; errors are thrown by consumers using node positions. - -Extension points: -- Add new node structs and wire them into `ASTVisitor` plus inline `accept` helpers. -- Keep node fields minimal and source-driven; avoid storing derived data here (belongs in semantics/runtime). - -Tests: -- `tests/test_ast.cpp` - -Related: -- `parser.md`, `semantics.md`, `runtime-evaluator.md` diff --git a/engineering/reference/builtins.md b/engineering/reference/builtins.md deleted file mode 100644 index 0685b31..0000000 --- a/engineering/reference/builtins.md +++ /dev/null @@ -1,25 +0,0 @@ -# Built-ins - -Bloch ships a small set of built-ins. These are treated like functions and validated by the -semantic analyser. - -## Console -- `echo(expr) -> void` — prints a human-friendly representation of `expr` to stdout. - -## Quantum gates -All return `void`. -- `h(qubit)` -- `x(qubit)` -- `y(qubit)` -- `z(qubit)` -- `rx(qubit, float)` -- `ry(qubit, float)` -- `rz(qubit, float)` -- `cx(qubit, qubit)` - -## Measurement/Reset -- `measure q` — expression form, accepts a single `qubit` and returns `bit`. -- `measure q;` — statement form, accepts `qubit` or `qubit[]`. -- `reset q;` — statement; accepts a single `qubit` and sets it to `|0>`. - -See also: [Language Specification](../../docs/language-spec.md). diff --git a/engineering/reference/cli.md b/engineering/reference/cli.md deleted file mode 100644 index e266cb0..0000000 --- a/engineering/reference/cli.md +++ /dev/null @@ -1,42 +0,0 @@ -# CLI Entry -Source: `src/main.cpp`, `src/bloch/cli/cli.*` - -Inputs: -- CLI arguments: `--help`, `--version`, `--update`, `--emit-qasm`, `--shots=N` (to be deprecated in v2.0.0), `--echo=auto|all|none`, `` -- Build-time defines: `BLOCH_VERSION`, `BLOCH_COMMIT_HASH` - -Outputs: -- Process exit code (0 on success) -- Echo/tracked output to stdout/stderr -- `.qasm` written alongside the source -- Background update check (stderr notice on availability) -- Refreshed stdlib installation on successful `--update` - -Behaviour: -The CLI parses flags, validates shot and echo options, and warns when `--shots=N` conflicts with -`@shots`. It runs a non-blocking update check on startup and can self-update when requested. -Before loading modules, it builds stdlib search paths from `BLOCH_STDLIB_PATH`, platform install -locations, binary-adjacent `share/bloch` directories, and local `library`/`stdlib` directories. -After parsing, it invokes the module loader, semantic analyser, and runtime interpreter to execute -the program. Multi-shot mode reruns the interpreter, aggregates tracked values, prints per-variable -summaries, and preserves the last shot’s QASM. Echo defaults to `auto`, suppressing output during -large shot counts unless explicitly overridden. `--update` replaces the binary and installs the -bundled stdlib into the resolved user-local library root. - -Invariants/Guarantees: -- Requires a single input file; errors out with usage on missing file. -- Always writes QASM, even when `--emit-qasm` is off (file only). -- Exits early after `--help`/`--version`/`--update`. - -Edge Cases/Errors: -- Invalid `--shots` (non-positive) or mismatched `--shots` vs. `@shots` produce warnings/errors as applicable. -- Exceptions from lower layers are caught and printed with a “Stopping program execution...” prefix. - -Extension points: -- Add flags by extending `kCliOptions` and the argument loop; ensure semantics/runtime support the feature. - -Tests: -- `tests/test_main.cpp` and `tests/test_integration.cpp` - -Related: -- `update-manager.md`, `module-loader.md`, `runtime-evaluator.md` diff --git a/engineering/reference/codebase-overview.md b/engineering/reference/codebase-overview.md deleted file mode 100644 index 2b0166e..0000000 --- a/engineering/reference/codebase-overview.md +++ /dev/null @@ -1,36 +0,0 @@ -# Codebase Overview - -This document gives a high-level map of the Bloch codebase and the execution pipeline. - -## High-level flow -1. **Module loader** resolves imports and merges modules. -2. **Lexer** tokenizes source and tracks line/column. -3. **Parser** builds the AST. -4. **Semantic analysis** validates types, annotations, and class rules. -5. **Runtime evaluator** interprets the AST and drives the quantum simulator. -6. **QASM output** is emitted alongside the input file. - -## Repository layout -- `src/bloch/compiler/` — lexer, parser, AST, semantic analysis, imports. -- `src/bloch/cli/` — CLI entry and option parsing. -- `src/bloch/http/` — HTTP helpers (used by update flows). -- `src/bloch/runtime/` — interpreter, runtime values, simulator. -- `src/bloch/support/` — diagnostics, logging, shared utilities. -- `src/bloch/update/` — self-update and version checks. -- `tests/` — unit, semantic, runtime, and integration tests. -- `examples/` — runnable Bloch programs. -- `docs/` — user documentation. -- `engineering/` — contributor docs, ADRs, and designs. - -## Key entry points -- `src/main.cpp` — Thin process entry point that forwards to CLI runtime. -- `src/bloch/cli/cli.*` — CLI parsing, update checks, stdlib path resolution, and execution flow. -- `src/bloch/compiler/import/module_loader.*` — import resolution and merge. -- `src/bloch/compiler/semantics/semantic_analyser.*` — compile-time rules. -- `src/bloch/runtime/runtime_evaluator.*` — interpreter and simulator integration. - -## Further reading -- [Architecture](./architecture.md) -- [Parser](./parser.md) -- [Semantics](./semantics.md) -- [Runtime Evaluator](./runtime-evaluator.md) diff --git a/engineering/reference/coding-standards.md b/engineering/reference/coding-standards.md deleted file mode 100644 index e98cb61..0000000 --- a/engineering/reference/coding-standards.md +++ /dev/null @@ -1,35 +0,0 @@ -# Coding Standards - -Inputs: -- New or edited code across the repo - -Outputs: -- Consistent, readable code and diagnostics - -Behaviour: -Favour clarity over micro-optimisation and extract helpers when functions mix concerns. Use RAII -for ownership and avoid raw allocation except where custom deleters are required for runtime -objects. Keep data flow explicit by passing state rather than relying on globals. Surface -user-facing failures with `BlochError` that includes category and source location; don’t -swallow exceptions. Where concurrency exists, guard shared structures such as the GC heap with -mutexes or atomics and keep critical sections short. Namespaces mirror folders, includes are -ordered with standard headers before project headers, and new features ship with matching tests -and doc updates across `docs/` and `engineering/reference/`. - -Invariants/Guarantees: -- No non-ASCII in code unless required by existing files. -- CLI output remains single-line per message; echo buffering preserves warning-first ordering. - -Edge Cases/Errors: -- Avoid adding concurrency around interpreter execution without locks; GC and interpreter share - state. - -Extension points: -- When introducing new subsystems, add their own reference doc and update - `engineering/reference/README.md`. - -Tests: -- Enforced socially via reviews; no automated enforcement in-tree. - -Related: -- `testing.md` diff --git a/engineering/reference/how-to-contribute.md b/engineering/reference/how-to-contribute.md deleted file mode 100644 index 583c235..0000000 --- a/engineering/reference/how-to-contribute.md +++ /dev/null @@ -1,46 +0,0 @@ -# How to Contribute - -Thanks for your interest in Bloch! This guide mirrors the contribution style used by mature -open-source projects: start small, keep changes focused, and communicate early. - -## Ways to contribute -- Fix bugs or implement features in the compiler/runtime. -- Improve docs in `docs/` or contributor references here. -- Add or expand tests in `tests/`. -- Triage issues and propose design changes in `engineering/designs/`. - -## Before you start -- Check existing issues and discussions for context. -- If you plan a larger change, open an issue or design doc first to align on scope. - -## Development setup -```bash -git clone https://github.com/bloch-labs/bloch.git -cd bloch -cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -cmake --build build --parallel -ctest --test-dir build --output-on-failure -``` - -Run the compiler against an example: -```bash -./build/bin/bloch examples/02_bell_state.bloch --emit-qasm -``` - -## Workflow -1. Create a feature branch. -2. Make focused changes with tests. -3. Update docs in `docs/` or `engineering/reference/` when behaviour changes. -4. Open a PR with a clear summary and test coverage notes. - -## PR checklist -- Tests pass locally (use `./scripts/build_and_test.sh`). -- Code is formatted (use `./scripts/format.sh`). -- New behaviour is covered by tests. -- Docs updated when user-facing behaviour changes. -- Follow the [Coding Standards](./coding-standards.md). - -## Where to look next -- [Codebase Overview](./codebase-overview.md) -- [Architecture](./architecture.md) -- [Testing](./testing.md) diff --git a/engineering/reference/lexer.md b/engineering/reference/lexer.md deleted file mode 100644 index 647c2d2..0000000 --- a/engineering/reference/lexer.md +++ /dev/null @@ -1,36 +0,0 @@ -# Lexer -Source: `src/bloch/compiler/lexer/lexer.hpp`, `src/bloch/compiler/lexer/lexer.cpp`, `src/bloch/compiler/lexer/token.hpp` - -Inputs: -- Raw source text (`std::string_view`) from a `.bloch` file - -Outputs: -- Flat `std::vector` including a trailing `Eof` token -- `BlochError` on lexical failures with `Lexical` category. - -Behaviour: -The lexer runs a single forward pass with minimal lookahead, turning characters into tokens while -skipping whitespace and `//` comments. It recognises ints, longs with an `L` suffix, floats with -an `f` suffix (e.g., `3f` or `3.14f`), bits restricted to `0b`/`1b`, strings (no escapes yet), -and single-character chars. -Keywords cover primitives, control flow, the class system, annotations, and built-ins. Line and -column are recorded per token, with the column pointing to the token start to make diagnostics -precise. - -Invariants/Guarantees: -- Always appends exactly one `Eof` token. -- Rejects malformed float literals (missing `f`) and bit literals other than `0b`/`1b`. -- Treats `//` to end-of-line as a comment; no block comments. - -Edge Cases/Errors: -- Unterminated string/char throws a `Lexical` `BlochError`. -- Unknown characters emit `Unknown` tokens (parser will surface errors later). - -Extension points: -- Add keywords/tokens in `TokenType` and the keyword map in `scanIdentifierOrKeyword`. - -Tests: -- `tests/test_lexer.cpp` - -Related: -- `parser.md`, `ast.md`, `semantics.md` diff --git a/engineering/reference/module-loader.md b/engineering/reference/module-loader.md deleted file mode 100644 index 5fa584f..0000000 --- a/engineering/reference/module-loader.md +++ /dev/null @@ -1,38 +0,0 @@ -# Module Loader -Source: `src/bloch/compiler/import/module_loader.hpp`, `src/bloch/compiler/import/module_loader.cpp` - -Inputs: -- Entry file path passed from the CLI -- Optional search paths (constructor argument) - -Outputs: -- Merged `Program` containing all classes/functions/statements from entry + imports -- `BlochError` with `Semantic`/`Parse` category on missing modules or cycles - -Behaviour: -The loader resolves default-package imports (for example `import Foo;`), dotted imports -(`import pkg.Foo;`), and wildcard imports (`import pkg.*;`). Default resolution order is importing -file directory, then configured search paths, then working directory. For `bloch.*` imports, search -paths are checked first to prevent project-local shadowing of stdlib modules. The loader keeps a -stack to detect cycles and surfaces the full chain when one appears. Each module is parsed only -once and cached; after loading, classes, functions, and statements are merged in load order into -a single `Program`. It auto-loads `bloch.lang.Object` before the entry file when available, -enforces that only one `main()` exists across the merged graph, captures any `@shots` decoration -on `main`, validates that imported files declare the expected `package`, and strips import nodes -before handing control to later phases. - -Invariants/Guarantees: -- Each module is parsed at most once per load invocation. -- If a module is missing or a cycle exists, loading aborts with an error; no partial programs are returned. - -Edge Cases/Errors: -- Multiple `main()` definitions across modules error out. -- Unresolved import paths include the qualified name in diagnostics. -- Wildcard imports error if the directory contains no `.bloch` files. -- Package mismatch errors include both the expected and actual package names. - -Tests: -- `tests/test_runtime.cpp` - -Related: -- `parser.md`, `semantics.md`, `runtime-evaluator.md`, `cli.md` diff --git a/engineering/reference/parser.md b/engineering/reference/parser.md deleted file mode 100644 index ebaab63..0000000 --- a/engineering/reference/parser.md +++ /dev/null @@ -1,36 +0,0 @@ -# Parser -Source: `src/bloch/compiler/parser/parser.hpp`, `src/bloch/compiler/parser/parser.cpp` - -Inputs: -- `std::vector` from the lexer - -Outputs: -- `std::unique_ptr` abstract syntax tree (AST) -- `BlochError` with `Parse` category on syntax errors. - -Behaviour: -Parsing is a hand-written recursive descent pass with light lookahead for types and an overflow -queue to expand multi-declared qubits. It constructs the AST defined in `ast/ast.hpp` and stamps -every node with its source position. The parser enforces file-header ordering (`package` then -imports, both only at top level), supports both default-package and dotted imports, enforces -annotation placement, static-class restrictions, constructor/destructor syntax (including -`= default`), and rejects obviously invalid forms like negative array index literals. Deeper -meaning (types, visibility, override correctness) is left to the semantic analyser. - -Invariants/Guarantees: -- Always consumes to `Eof` or throws; no partial trees. -- Multi-declared qubits (e.g., `qubit a, b;`) are expanded into separate declarations in order. - -Edge Cases/Errors: -- Reports missing tokens (`expect`) with targeted messages (e.g., missing `;`, `)`). -- Rejects invalid annotations eagerly to avoid confusing downstream errors. - -Extension points: -- Add productions by extending the relevant parse* method; keep expression precedence consistent with existing helpers. -- When adding syntax that introduces nodes, also extend AST definitions and semantic/runtime handling. - -Tests: -- `tests/test_parser.cpp` - -Related: -- `lexer.md`, `ast.md`, `semantics.md` diff --git a/engineering/reference/qasm-mapping.md b/engineering/reference/qasm-mapping.md deleted file mode 100644 index ff04b06..0000000 --- a/engineering/reference/qasm-mapping.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: QASM Mapping ---- -# QASM Mapping - -Bloch emits OpenQASM 2.0 for quantum operations performed by the interpreter and simulator. The CLI always writes `.qasm` next to your source; use `--emit-qasm` to also print it to stdout. - -## Gate mappings - -Single-qubit gates: - -| Bloch | OpenQASM | -| --- | --- | -| `h(q)` | `h q[i];` | -| `x(q)` | `x q[i];` | -| `y(q)` | `y q[i];` | -| `z(q)` | `z q[i];` | -| `rx(q, theta)` | `rx(theta) q[i];` | -| `ry(q, theta)` | `ry(theta) q[i];` | -| `rz(q, theta)` | `rz(theta) q[i];` | - -Two-qubit gate: - -| Bloch | OpenQASM | -| --- | --- | -| `cx(ctrl, tgt)` | `cx q[c], q[t];` | - -Notes -- `q[i]` refers to the underlying simulator qubit at index `i`. When using single `qubit` variables, the simulator assigns an index for that allocation; when using `qubit[]`, `q[k]` maps directly to an index. -- Rotation angles are emitted as-is (float values in radians). - -## Measurement and classical bits - -- Statement form: `measure q;` becomes `measure q[i] -> c[i];` in the log and collapses the qubit. -- Statement form on `qubit[]` emits one measurement line per element, in index order. -- Expression form: `bit b = measure q;` accepts a single `qubit`, produces a measurement result, - and returns a `bit` value to the program. - -The simulator maintains a classical register `c[...]` for recorded outcomes in the QASM log. - -## Example - -Bloch: - -``` -@quantum -function bell(qubit a, qubit b) -> void { - h(a); cx(a, b); -} - -function main() -> void { - qubit q0; qubit q1; - bell(q0, q1); - measure q0; measure q1; -} -``` - -Emitted QASM: - -``` -OPENQASM 2.0; -include "qelib1.inc"; -qreg q[2]; -creg c[2]; -h q[0]; -cx q[0],q[1]; -measure q[0] -> c[0]; -measure q[1] -> c[1]; -``` - -See also -- Built-ins and signatures: [Built-ins](./builtins.md) -- Runtime and simulator details: [Runtime Evaluator](./runtime-evaluator.md) and [QASM Simulator](./qasm-simulator.md) diff --git a/engineering/reference/qasm-simulator.md b/engineering/reference/qasm-simulator.md deleted file mode 100644 index 8c613f5..0000000 --- a/engineering/reference/qasm-simulator.md +++ /dev/null @@ -1,33 +0,0 @@ -# QASM Simulator -Source: `src/bloch/runtime/qasm_simulator.hpp`, `src/bloch/runtime/qasm_simulator.cpp` - -Inputs: -- Gate invocations from the runtime (`h`, `x`, `y`, `z`, `rx`, `ry`, `rz`, `cx`) -- Qubit indices allocated by the runtime -- Reset and measure requests - -Outputs: -- Updated statevector -- OpenQASM log (header + qreg/creg + gate statements) when logging is enabled -- Measurement results (ints) returned to runtime -- `BlochError` with `Runtime` category on invalid operations - -Behaviour: -The simulator keeps an ideal statevector, doubling its size for each allocated qubit and zeroing the |1> subspace. Gates are applied with blocked matrix multiplication and minimal branching. Measurement samples the appropriate probability, collapses the state, and marks qubits so later gate calls on measured qubits fail fast. Reset renormalises the |0> subspace, clears measurement marks, and allows index reuse. QASM logging is optional per evaluator instance; even when logging is off, register declarations still reflect the allocated qubits. - -Invariants/Guarantees: -- Throws on invalid qubit indices or gate calls on measured qubits. -- `stateSize()` is always a power of two, matching the number of allocated qubits. - -Edge Cases/Errors: -- Division by zero is not present in gate math; main risks are invalid indices and post-measurement operations. -- Logging suppression only affects gate lines; register declarations still reflect allocated qubits. - -Extension points: -- Add new gates by implementing matrix application and QASM emission; ensure runtime dispatch matches. - -Tests: -- `tests/test_runtime.cpp` - -Related: -- `runtime-evaluator.md`, `semantics.md` diff --git a/engineering/reference/runtime-evaluator.md b/engineering/reference/runtime-evaluator.md deleted file mode 100644 index 2ba12c4..0000000 --- a/engineering/reference/runtime-evaluator.md +++ /dev/null @@ -1,36 +0,0 @@ -# Runtime Evaluator -Source: `src/bloch/runtime/runtime_evaluator.hpp`, `src/bloch/runtime/runtime_evaluator.cpp` - -Inputs: -- Semantically valid AST `Program` -- CLI options (emit-qasm, shots, echo) forwarded by `src/bloch/cli/cli.cpp` - -Outputs: -- Program side effects: echo output, tracked aggregation, QASM log -- Throws `BlochError` with `Runtime` category on runtime failures - -Behaviour: -`RuntimeEvaluator` is a single-use interpreter. On `execute`, it builds runtime class metadata, initialises static fields, and starts a GC worker only when classes are present. It walks statements and expressions with an environment stack, class table, and heap, delegating quantum operations to the simulator and validating qubit usage (allocation, measurement, reset, and post-measurement guards). Tracked variables and fields record outcomes when scopes close, and multi-shot runs aggregate those counts. Constructors/destructors honour inheritance—`super(...)` chaining, default constructors binding parameters to fields, vtables for virtual dispatch, and base-first destructor execution unless skipped by the cycle collector. Echo output is buffered so warnings appear before user logs. - -Invariants/Guarantees: -- Throws if reused (`execute` is single-use). -- Static field initialisers run once per class; instance field initialisers run during construction. -- Virtual dispatch uses vtable indices to honour overrides. -- QASM logging can be suppressed per evaluator instance. - -Edge Cases/Errors: -- Out-of-bounds array indexing, invalid casts, or post-measurement gate usage raise `BlochError`. -- Cycle collector skips destructors for unreachable cycles without tracked fields and retains cycles with tracked fields (intentional trade-off). -- Runtime truthiness supports `boolean`, `bit`, `int`, `long`, and `float`, but semantic analysis restricts conditions to `boolean` or `bit`. -- Methods with non-void return types are not enforced to return a value (open issue). - -Extension points: -- Add new value kinds: extend `Value::Type`, default initialisation, assignment/lookup semantics, and expression evaluation. -- Add new statements/expressions: extend `exec`/`eval` with line/column-aware errors. -- Integrate new backends: replace or wrap `QasmSimulator` while preserving the interface used here. - -Tests: -- `tests/test_runtime.cpp` - -Related: -- `qasm-simulator.md`, `semantics.md`, `module-loader.md`, `cli.md` diff --git a/engineering/reference/semantics.md b/engineering/reference/semantics.md deleted file mode 100644 index 7b8eafc..0000000 --- a/engineering/reference/semantics.md +++ /dev/null @@ -1,44 +0,0 @@ -# Semantic Analyser -Source: `src/bloch/compiler/semantics/semantic_analyser.hpp`, `src/bloch/compiler/semantics/semantic_analyser.cpp`, `src/bloch/compiler/semantics/type_system.*`, `src/bloch/compiler/semantics/built_ins.*` - -Inputs: -- AST `Program` from the parser - -Outputs: -- Populated symbol tables and metadata (function signatures, class registry) -- Updated AST (array sizes resolved from const expressions) -- `BlochError` with `Semantic` category on failure - -Behaviour: -The semantic analyser walks the AST with a scoped `SymbolTable`, recording declared names, their -types, `final` status, and any const-int values used for array sizing. It validates declarations, -visibility, static-versus-instance usage, and inheritance rules (single base, override/virtual -correctness, abstract methods). Constructors and destructors are checked for default binding -shape, parameter-field alignment, and uniqueness. Annotations are enforced—`@quantum` return -types, `@shots` only on `main`, and `@tracked` restricted to variable/field annotations—and -arrays must have compile-time, non-negative sizes with `qubit[]` barred from literal -initialisation. Expression types are inferred to ensure assignments, returns, calls, casts, -member access, and control-flow conditions are consistent. Built-in gate signatures are -registered so runtime dispatch can trust the shapes. - -Invariants/Guarantees: -- Every declared name is unique within scope; redeclarations fail. -- Class registry is built before analysis; missing bases or cycles error out. -- Functions are predeclared to allow call-before-definition. - -Edge Cases/Errors: -- Casts are only allowed between `int`, `long`, `float`, and `bit`; all other casts are rejected. -- Control-flow conditions must be `boolean` or `bit` (numeric truthiness is rejected). -- Non-`void` top-level functions must contain at least one `return` with a value. -- Methods currently do not enforce “must return a value” for non-void return types (open issue). - -Extension points: -- Add new primitives: extend `ValueType`, `typeFromString/typeToString`, and inference paths. -- Add new annotations or rules: extend validation in relevant `visit` methods. -- Add new built-ins: extend `built_in_gates` and keep runtime/simulator in sync. - -Tests: -- `tests/test_semantics.cpp` - -Related: -- `ast.md`, `parser.md`, `runtime-evaluator.md` diff --git a/engineering/reference/support-and-errors.md b/engineering/reference/support-and-errors.md deleted file mode 100644 index 5850828..0000000 --- a/engineering/reference/support-and-errors.md +++ /dev/null @@ -1,29 +0,0 @@ -# Support & Errors -Source: `src/bloch/support/error/bloch_error.hpp` - -Inputs: -- Messages, line/column (when available), and error categories from callers - -Outputs: -- Formatted coloured strings for stderr/stdout -- `BlochError` exceptions carrying category, line, column - -Behaviour: -This layer formats diagnostics with ANSI colours and consistent prefixes, exposing helpers for info and warning logs and a `BlochError` exception that carries category and source location. Messages reset colours after each line to avoid bleeding styles, and callers pass line/column when available so errors map directly to source. - -Invariants/Guarantees: -- Colour codes are reset after each message to avoid leaking styling. -- If line/column are zero, locations are omitted from formatted messages. - -Edge Cases/Errors: -- None internally; relies on caller-supplied data. Consumers must avoid throwing with invalid UTF-8 (all code uses ASCII). - -Extension points: -- Add new categories to `ErrorCategory` if new phases are introduced; ensure format helpers cover them. -- For non-colour environments, gate colour output behind an environment check. - -Tests: -- Indirect via semantics/runtime/CLI tests that assert on error messages and locations. - -Related: -- `semantics.md`, `runtime-evaluator.md`, `cli.md` diff --git a/engineering/reference/testing.md b/engineering/reference/testing.md deleted file mode 100644 index 1a97a38..0000000 --- a/engineering/reference/testing.md +++ /dev/null @@ -1,24 +0,0 @@ -# Testing -Source: `tests/*`, `scripts/build_and_test.sh` - -Inputs: -- Built test binaries via CMake - -Outputs: -- Pass/fail results; diagnostics from assertions - -Behaviour: -The suite is split into focused unit tests and integration runs. Unit suites cover lexing, parsing, semantics, runtime, and AST shapes through files like `tests/test_lexer.cpp`, `tests/test_parser.cpp`, `tests/test_semantics.cpp`, `tests/test_runtime.cpp`, and `tests/test_ast.cpp`. Integration coverage in `tests/test_integration.cpp` and `tests/test_main.cpp` exercises CLI and end-to-end flows. All tests share the lightweight harness in `tests/test_framework.hpp`, and you can run them with `ctest --test-dir build --output-on-failure` or via `scripts/build_and_test.sh`. - -Invariants/Guarantees: -- Tests assume deterministic simulator RNG seed from `std::random_device`; quantum randomness is still probabilistic, so assertions avoid brittle probability checks. - -Edge Cases/Errors: -- Tests that expect errors often assert on `BlochError` line/column; keep those stable when editing parser/semantics. - -Extension points: -- Add cases to existing suites rather than creating new files to keep coverage discoverable. -- For new language/runtime features, add coverage across relevant layers (lexer/parser/semantics/runtime). - -Related: -- `coding-standards.md` diff --git a/engineering/reference/update-manager.md b/engineering/reference/update-manager.md deleted file mode 100644 index a19a139..0000000 --- a/engineering/reference/update-manager.md +++ /dev/null @@ -1,34 +0,0 @@ -# Update Manager -Source: `src/bloch/update/update_manager.hpp`, `src/bloch/update/update_manager.cpp` - -Inputs: -- Current version string from CLI (`BLOCH_VERSION`) -- Executable path (`argv0`) for self-update -- Environment: `BLOCH_NO_UPDATE_CHECK`, `BLOCH_OFFLINE`, `CI` to disable checks - -Outputs: -- Console notices when newer releases exist -- Updated binary in place on successful `--update` -- Installed or refreshed bundled stdlib in the resolved library root on successful `--update` -- On-disk cache file (platform-appropriate cache dir) for version metadata - -Behaviour: -`checkForUpdatesIfDue` is a rate-limited probe (every 72h) that fetches the latest GitHub release tag and emits a one-line notice when a newer version exists, skipping entirely in CI/offline/opt-out environments. `performSelfUpdate` downloads the platform-specific archive, optionally verifies checksums, extracts it, and replaces the running binary—in PowerShell on Windows and via `tar` on POSIX—prompting before major upgrades. Both paths rely on `cpp-httplib` over HTTPS with OpenSSL and validate HTTP status codes before acting. After extraction, the updater also locates the bundled stdlib in the release archive and copies it into the resolved stdlib root, updating both the unversioned root and a versioned subdirectory for the installed release. - -Invariants/Guarantees: -- Never downgrades: if current >= latest, exits with success notice. -- Leaves existing binary untouched on download/verify failures. - -Edge Cases/Errors: -- Network/HTTP errors print friendly messages and abort updates. -- Unsupported OS/arch combinations reject with a clear error. - -Extension points: -- Add new platforms by extending `osLabel/archLabel` and download asset naming. -- Adjust rate-limiting or cache location by modifying `kUpdateWindow`/`cacheFilePath`. - -Tests: -- Exercised indirectly via CLI integration tests; network calls are not mocked in current suite. - -Related: -- `cli.md`, `support-and-errors.md` diff --git a/examples/README.md b/examples/README.md index 618b166..df4d3fe 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,17 +1,17 @@ -# Bloch Examples +# Basis Examples -This folder contains small example Bloch programs designed to teach syntax and help you get started with algorithm creation in Bloch. +This folder contains small example Basis programs designed to teach syntax and help you get started with algorithm creation in Basis. ## How to run -Bloch executes a single `.bloch` file at a time. +Basis executes a single `.bloch` file at a time. ```bash # Single run (default is 1 shot) -bloch examples/01_hadamard.bloch +basis examples/01_hadamard.bloch # Multi-shot run (aggregates results across shots) -bloch examples/01_hadamard.bloch --shots=1024 +basis examples/01_hadamard.bloch --shots=1024 ``` **Notes** @@ -36,14 +36,14 @@ bloch examples/01_hadamard.bloch --shots=1024 **Try:** ```bash -bloch examples/01_hadamard.bloch --shots=1024 +basis examples/01_hadamard.bloch --shots=1024 ``` **Expected output:** ``` [INFO]: suppressing echo; to view them use --echo=all Shots: 1024 -Backend: Bloch Ideal Simulator +Backend: Basis Ideal Simulator Elapsed: 0.003s qubit q @@ -59,14 +59,14 @@ outcome | count | prob **Try:** ```bash -bloch examples/02_bell_state.bloch --shots=1024 +basis examples/02_bell_state.bloch --shots=1024 ``` **Expected output:** ``` [INFO]: suppressing echo; to view them use --echo=all Shots: 1024 -Backend: Bloch Ideal Simulator +Backend: Basis Ideal Simulator Elapsed: 0.010s qubit[] qreg @@ -82,7 +82,7 @@ outcome | count | prob **Try:** ```bash -bloch examples/03_deutsch_jozsa.bloch +basis examples/03_deutsch_jozsa.bloch ``` **Expected output:** @@ -101,14 +101,14 @@ Deutsch-Jozsa balanced oracle measurement: **Try:** ```bash -bloch examples/04_grover_search.bloch --shots=1024 +basis examples/04_grover_search.bloch --shots=1024 ``` **Expected output:** ``` [INFO]: suppressing echo; to view them use --echo=all Shots: 1024 -Backend: Bloch Ideal Simulator +Backend: Basis Ideal Simulator Elapsed: 0.147s qubit[] data @@ -125,7 +125,7 @@ outcome | count | prob **Try:** ```bash -bloch examples/05_teleport_class.bloch --shots=512 +basis examples/05_teleport_class.bloch --shots=512 ``` Prepares a |+> state to teleport, builds a Bell pair via the `Teleporter` class, measures the sender, and applies classical corrections to the receiver. @@ -141,7 +141,7 @@ Across many shots, the receiver’s outcome matches the input state (here |+>, s **Try:** ```bash -bloch examples/06_maxcut_c4_class.bloch --shots=1024 +basis examples/06_maxcut_c4_class.bloch --shots=1024 ``` Encapsulates a p=1 QAOA for the 4-node cycle. Constructor captures `(gamma, beta)`; `run` builds |+>^4, applies the cost on edges (0,1), (1,2), (2,3), (3,0), then a mixer. @@ -153,7 +153,7 @@ Encapsulates a p=1 QAOA for the 4-node cycle. Constructor captures `(gamma, beta **Try:** ```bash -bloch examples/07_null_demo.bloch +basis examples/07_null_demo.bloch ``` This example demonstrates null reference in a user created class. While primitives are non-nullable, class members can be initialised to null. @@ -164,7 +164,7 @@ This example demonstrates null reference in a user created class. While primitiv **Try:** ```bash -bloch examples/08_generics.bloch +basis examples/08_generics.bloch ``` This demonstrates the usage of generics in user classes. @@ -175,7 +175,7 @@ This demonstrates the usage of generics in user classes. **Try:** ```bash -bloch examples/09_generic_inheritance.bloch +basis examples/09_generic_inheritance.bloch ``` `MeasuredReadout` extends `Sample`. Its `super(measured)` call is an @@ -190,7 +190,7 @@ acceptance example for generic inheritance: the compiler must substitute Shows how to split code across files: `main.bloch` imports the static `QuantumMath` helper from `package com.example` and uses it to estimate a two-level system’s energy gap and phase accumulation. **Try:** ```bash -bloch examples/multifile/main.bloch +basis examples/multifile/main.bloch ``` **Expected output (representative):** ``` @@ -202,7 +202,7 @@ Phase after 100 us (rad): 125663.7030 ## FAQ **Do I need a `main()` function?** -Yes. The Bloch runtime looks up a function literally named `main` and uses it as the entry point. Any other functions you define have to be called (directly or indirectly) from `main`, otherwise they are never executed. `@tracked` counts are collected when a scope ends, so without running `main` the tracked qubits never leave scope and nothing is printed. +Yes. The Basis runtime looks up a function literally named `main` and uses it as the entry point. Any other functions you define have to be called (directly or indirectly) from `main`, otherwise they are never executed. `@tracked` counts are collected when a scope ends, so without running `main` the tracked qubits never leave scope and nothing is printed. **What does `@tracked` do?** It aggregates measurement outcomes for the annotated qubit array across shots and prints counts/probabilities. diff --git a/examples/multifile/main.qasm b/examples/multifile/main.qasm deleted file mode 100644 index 11c832c..0000000 --- a/examples/multifile/main.qasm +++ /dev/null @@ -1,4 +0,0 @@ -OPENQASM 2.0; -include "qelib1.inc"; -qreg q[0]; -creg c[0]; diff --git a/justfile b/justfile new file mode 100644 index 0000000..410680f --- /dev/null +++ b/justfile @@ -0,0 +1,33 @@ +set shell := ["bash", "-euo", "pipefail", "-c"] +set positional-arguments + +default: + @just --list + +configure: + cmake --preset dev + +build: configure + cmake --build --preset dev --parallel 2 + +test: build + ctest --preset dev + +run +args: build + ./build/dev/bin/basis "$@" + +format: + bash scripts/format.sh + +format-check: + bash scripts/format.sh --check + +check: format-check + cmake --preset ci + cmake --build --preset ci --parallel 2 + ctest --preset ci + bash scripts/run_examples.sh build/ci/bin/basis + bash scripts/check-install.sh build/ci + +install *args: + bash scripts/install.sh "$@" diff --git a/paper/paper.md b/paper/paper.md index fc3575a..4fcb756 100644 --- a/paper/paper.md +++ b/paper/paper.md @@ -181,12 +181,12 @@ experiments. Current use cases include: # Availability -Bloch is openly developed at https://github.com/bloch-labs/bloch under the +Bloch is openly developed at https://github.com/akshaysoftware/basis under the Apache-2.0 license. The repository bundles setup instructions, contribution guidelines, and a list of feature flags so that new contributors can propose language extensions while maintaining release stability. Pre-built binaries are available but not required; the CMake toolchain builds the CLI across major platforms, and the -project's documentation hub (https://docs.bloch-labs.com) provides user guides and API +project's documentation hub (https://github.com/akshaysoftware/basis/tree/main/docs) provides user guides and API notes. # Acknowledgements diff --git a/release-please-config.json b/release-please-config.json deleted file mode 100644 index 5ead456..0000000 --- a/release-please-config.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", - "include-v-in-tag": true, - "include-component-in-tag": false, - "changelog-sections": [ - { "type": "feat", "section": "⚛️ Features", "hidden": false }, - { "type": "fix", "section": "🐛 Bug Fixes", "hidden": false }, - { "type": "perf", "section": "⚡ Performance", "hidden": false } - ], - "packages": { - ".": { - "release-type": "simple", - "package-name": "bloch" - } - } -} diff --git a/scripts/build_and_test.sh b/scripts/build_and_test.sh deleted file mode 100755 index d41320e..0000000 --- a/scripts/build_and_test.sh +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/env bash - -# Build and test Bloch on macOS/Linux. -# Runs: -# cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -# cmake --build build --parallel -# ctest --test-dir build --output-on-failure -# scripts/run_examples.sh build/bin/bloch - -if [ -z "${BASH_VERSION:-}" ]; then - echo "This script requires bash (macOS/Linux)." >&2 - exit 1 -fi - -set -euo pipefail - -if [[ "$(uname -s)" != "Linux" && "$(uname -s)" != "Darwin" ]]; then - echo "Unsupported OS: $(uname -s). This script is for macOS/Linux only." >&2 - exit 1 -fi - -# Pretty output helpers -if [[ -t 1 && "${NO_COLOR:-}" != "1" ]]; then - RED="\033[31m"; GREEN="\033[32m"; YELLOW="\033[33m"; BLUE="\033[34m"; BOLD="\033[1m"; RESET="\033[0m" -else - RED=""; GREEN=""; YELLOW=""; BLUE=""; BOLD=""; RESET="" -fi - -step() { printf "%b➜%b %s\n" "$BLUE" "$RESET" "$*"; } -success() { printf "%b✓%b %s\n" "$GREEN" "$RESET" "$*"; } -warn() { printf "%b!%b %s\n" "$YELLOW" "$RESET" "$*" >&2; } -error() { printf "%b✗%b %s\n" "$RED" "$RESET" "$*" >&2; } - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" -BUILD_DIR="${BUILD_DIR:-${ROOT_DIR}/build}" -CONFIG="${CONFIG:-Release}" - -detect_jobs() { - if command -v nproc >/dev/null 2>&1; then - nproc - elif command -v sysctl >/dev/null 2>&1; then - sysctl -n hw.ncpu 2>/dev/null || echo 4 - else - echo 4 - fi -} -JOBS="${JOBS:-$(detect_jobs)}" - -require_cmd() { - command -v "$1" >/dev/null 2>&1 || { error "Required command '$1' not found in PATH."; exit 1; } -} - -require_cmd cmake -require_cmd ctest - -cache_internal_value() { - local key="$1" - local cache_file="$2" - local line - - line="$(grep -E "^${key}:INTERNAL=" "${cache_file}" 2>/dev/null || true)" - printf "%s\n" "${line#*=}" -} - -cmake_supports_fresh() { - cmake --help 2>/dev/null | grep -q -- "--fresh" -} - -CONFIGURE_ARGS=(-S "${ROOT_DIR}" -B "${BUILD_DIR}" -DCMAKE_BUILD_TYPE="${CONFIG}") - -if [[ -f "${BUILD_DIR}/CMakeCache.txt" ]]; then - CACHED_SOURCE_DIR="$(cache_internal_value CMAKE_HOME_DIRECTORY "${BUILD_DIR}/CMakeCache.txt")" - CACHED_BUILD_DIR="$(cache_internal_value CMAKE_CACHEFILE_DIR "${BUILD_DIR}/CMakeCache.txt")" - - if [[ "${CACHED_SOURCE_DIR}" != "${ROOT_DIR}" || "${CACHED_BUILD_DIR}" != "${BUILD_DIR}" ]]; then - warn "Detected stale CMake cache for a different checkout path." - warn "Cached source: ${CACHED_SOURCE_DIR:-unknown}" - warn "Cached build: ${CACHED_BUILD_DIR:-unknown}" - - if cmake_supports_fresh; then - warn "Reconfiguring with 'cmake --fresh' to rebuild CMake metadata." - CONFIGURE_ARGS=(--fresh "${CONFIGURE_ARGS[@]}") - else - warn "Removing stale CMake cache files before reconfiguring." - cmake -E rm -f \ - "${BUILD_DIR}/CMakeCache.txt" \ - "${BUILD_DIR}/CTestTestfile.cmake" \ - "${BUILD_DIR}/cmake_install.cmake" \ - "${BUILD_DIR}/compile_commands.json" - if [[ -d "${BUILD_DIR}/CMakeFiles" ]]; then - cmake -E remove_directory "${BUILD_DIR}/CMakeFiles" - fi - fi - fi -fi - -step "Configuring CMake (${CONFIG}) in ${BUILD_DIR}" -cmake "${CONFIGURE_ARGS[@]}" - -step "Building (parallel: ${JOBS})" -cmake --build "${BUILD_DIR}" --parallel "${JOBS}" - -step "Running unit and integration tests" -ctest --test-dir "${BUILD_DIR}" --output-on-failure - -step "Running acceptance tests" -"${SCRIPT_DIR}/run_examples.sh" "${BUILD_DIR}/bin/bloch" - -success "Build and tests completed successfully." diff --git a/scripts/check-install.sh b/scripts/check-install.sh new file mode 100755 index 0000000..179b7ba --- /dev/null +++ b/scripts/check-install.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/.." + +build_dir="${1:-build/ci}" +scratch="$(mktemp -d)" +trap 'rm -rf "$scratch"' EXIT + +cmake --install "$build_dir" --prefix "$scratch/prefix" +mkdir "$scratch/work" + +cat > "$scratch/work/smoke.bloch" <<'BLOCH' +function main() -> void { + qubit q; + x(q); + bit result = measure q; + echo(result); + Object object = new Object(); + echo(object.toString()); +} +BLOCH + +expected_version="$(cat version.txt)" +( + cd "$scratch/work" + unset BASIS_STDLIB_PATH + export PATH="$scratch/prefix/bin:$PATH" + + version="$(basis --version)" + [[ "$version" == "$expected_version"* ]] + + output="$(basis smoke.bloch)" + [[ "$output" == $'1\nbloch.lang.Object' ]] +) + +echo "Installed executable and bundled standard library passed the smoke test." diff --git a/scripts/format.sh b/scripts/format.sh index 937c1a8..f6a9884 100755 --- a/scripts/format.sh +++ b/scripts/format.sh @@ -1,58 +1,23 @@ #!/usr/bin/env bash - set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/.." -# Resolve repository root (directory containing this script's parent). -SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) -REPO_ROOT=$(cd "$SCRIPT_DIR/.." && pwd) - -# Allow overriding the binary via CLANG_FORMAT env var; default to clang-format-14. -CLANG_FORMAT_BIN=${CLANG_FORMAT:-clang-format-14} - -usage() { - cat <<'EOF' -Usage: scripts/format.sh [--check] - -Formats all C/C++ sources tracked by the repository's .clang-format file. - -Options: - --check Run clang-format in diff mode (no files are modified); exits non-zero - if any file would be reformatted. Mirrors the CI formatting check. - -Environment variables: - CLANG_FORMAT Override the clang-format binary (default: clang-format-14) -EOF -} - -if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then - usage - exit 0 +formatter="${BASIS_CLANG_FORMAT:-clang-format-18}" +if ! command -v "$formatter" >/dev/null 2>&1; then + formatter=clang-format fi -if ! command -v "$CLANG_FORMAT_BIN" >/dev/null 2>&1; then - echo "Error: '$CLANG_FORMAT_BIN' not found. Install clang-format-14 or set CLANG_FORMAT." >&2 +version="$("$formatter" --version)" +[[ "$version" == *"version 18."* ]] || { + echo "clang-format 18 is required; set BASIS_CLANG_FORMAT to its path." >&2 exit 1 -fi - -cd "$REPO_ROOT" - -mapfile -d '' sources < <(find . -regex '.*\.\(cpp\|hpp\|c\|h\)' -print0) +} -if [[ ${#sources[@]} -eq 0 ]]; then - echo "No C/C++ source files found." - exit 0 -fi +case "${1:-}" in + '') options=(-i) ;; + --check) options=(--dry-run --Werror) ;; + *) echo "Usage: $0 [--check]" >&2; exit 2 ;; +esac -if [[ ${1:-} == "--check" ]]; then - echo "Running clang-format check using '$CLANG_FORMAT_BIN'." - if ! printf '%s\0' "${sources[@]}" \ - | xargs -0 -r "$CLANG_FORMAT_BIN" -style=file -n --Werror; then - echo "Formatting issues detected. Rerun without --check to fix." >&2 - exit 1 - fi - echo "Formatting looks good." -else - echo "Formatting sources using '$CLANG_FORMAT_BIN'..." - printf '%s\0' "${sources[@]}" | xargs -0 -r "$CLANG_FORMAT_BIN" -style=file -i - echo "Done." -fi +find src tests -type f \( -name '*.cpp' -o -name '*.hpp' -o -name '*.h' \) -print0 | + xargs -0 "$formatter" "${options[@]}" diff --git a/scripts/install.ps1 b/scripts/install.ps1 deleted file mode 100644 index cb49626..0000000 --- a/scripts/install.ps1 +++ /dev/null @@ -1,121 +0,0 @@ -Param( - [string]$Version = "latest", - [string]$InstallDir = "$env:LOCALAPPDATA\Programs\Bloch", - [string]$LibraryDir = "$env:LOCALAPPDATA\Bloch\library" -) - -$ErrorActionPreference = "Stop" -[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 - -function Step($msg) { Write-Host "-> $msg" } -function Ok($msg) { Write-Host "[OK] $msg" -ForegroundColor Green } -function Warn($msg) { Write-Warning $msg } -function Fail($msg) { Write-Error $msg; exit 1 } - -$Repo = "bloch-labs/bloch" -$Tmp = New-Item -ItemType Directory -Path ([System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), "bloch-install-" + [System.Guid]::NewGuid().ToString("N"))) -Force -try { - function Resolve-Version { - param($inputVersion) - if ($inputVersion -eq "latest") { - $resp = Invoke-WebRequest -UseBasicParsing -Uri "https://api.github.com/repos/$Repo/releases/latest" - $json = $resp.Content | ConvertFrom-Json - if (-not $json.tag_name) { Fail "Could not resolve latest release tag" } - return $json.tag_name - } - elseif ($inputVersion -eq "latest-rc") { - $resp = Invoke-WebRequest -UseBasicParsing -Uri "https://api.github.com/repos/$Repo/releases" - $json = $resp.Content | ConvertFrom-Json - $rc = $json | Where-Object { $_.prerelease -eq $true } | Select-Object -First 1 - if (-not $rc) { Fail "Could not resolve latest prerelease tag" } - return $rc.tag_name - } - else { - return $inputVersion - } - } - - $Tag = Resolve-Version $Version - if (-not $Tag) { Fail "Empty tag resolved" } - - $Asset = "bloch-$Tag-Windows-X64.zip" - $BaseUrl = "https://github.com/$Repo/releases/download/$Tag" - $AssetUrl = "$BaseUrl/$Asset" - $ChecksumsUrl = "$BaseUrl/checksums-Windows-X64.txt" - - Step "Installing Bloch $Tag for Windows/X64 into $InstallDir" - Step "Downloading: $AssetUrl" - $assetPath = Join-Path $Tmp $Asset - Invoke-WebRequest -UseBasicParsing -Uri $AssetUrl -OutFile $assetPath - - $checksumPath = Join-Path $Tmp "checksums-Windows-X64.txt" - $haveChecksum = $true - try { - Invoke-WebRequest -UseBasicParsing -Uri $ChecksumsUrl -OutFile $checksumPath - } catch { - Warn "checksums-Windows-X64.txt not found; skipping verification" - $haveChecksum = $false - } - - if ($haveChecksum) { - Step "Verifying checksum (checksums-Windows-X64.txt)" - $expected = (Select-String -Path $checksumPath -Pattern " $Asset`$").Line -replace "\s+$Asset","" - if (-not $expected) { Warn "Expected checksum not found; skipping verification" } - else { - $actual = (Get-FileHash -Algorithm SHA256 -Path $assetPath).Hash.ToLower() - if ($expected.ToLower() -ne $actual) { - Fail "Checksum mismatch for $Asset`nExpected: $expected`nActual: $actual" - } else { - Ok "Checksum OK" - } - } - } - - Step "Extracting" - $extractDir = Join-Path $Tmp "extract" - Expand-Archive -LiteralPath $assetPath -DestinationPath $extractDir -Force - - $blochExe = Get-ChildItem -LiteralPath $extractDir -Recurse -Filter "bloch.exe" | Select-Object -First 1 - if (-not $blochExe) { Fail "Extracted archive did not contain bloch.exe" } - - if (-not (Test-Path $InstallDir)) { - New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null - } - $targetExe = Join-Path $InstallDir "bloch.exe" - Copy-Item -LiteralPath $blochExe.FullName -Destination $targetExe -Force - Ok "Installed: $targetExe" - - Step "Probing binary" - $probe = & $targetExe --version 2>$null - if ($LASTEXITCODE -ne 0) { Fail "Downloaded binary failed to run. Output: $probe" } - Ok $probe - - $stdlibDir = Get-ChildItem -LiteralPath $extractDir -Directory -Recurse | - Where-Object { $_.FullName -match '[\\/]share[\\/]bloch[\\/]library$' } | - Select-Object -First 1 - if ($stdlibDir) { - $versionLibraryDir = Join-Path $LibraryDir $Tag - New-Item -ItemType Directory -Path $LibraryDir -Force | Out-Null - New-Item -ItemType Directory -Path $versionLibraryDir -Force | Out-Null - Copy-Item -Path (Join-Path $stdlibDir.FullName "*") -Destination $LibraryDir -Recurse -Force - Copy-Item -Path (Join-Path $stdlibDir.FullName "*") -Destination $versionLibraryDir -Recurse -Force - Ok "Installed stdlib: $versionLibraryDir" - } else { - Warn "Bundled stdlib not found in archive; falling back to runtime built-ins only" - } - - # Add to user PATH if needed - $userPath = [Environment]::GetEnvironmentVariable("Path", "User") - $pathEntries = $userPath -split ";" | Where-Object { $_ -ne "" } - if ($pathEntries -notcontains $InstallDir) { - Step "Adding $InstallDir to user PATH" - $newPath = ($pathEntries + $InstallDir) -join ";" - [Environment]::SetEnvironmentVariable("Path", $newPath, "User") - Warn "PATH updated for future shells. Open a new PowerShell or CMD to use 'bloch' directly." - } else { - Ok "PATH already contains $InstallDir" - } - -} finally { - if (Test-Path $Tmp) { Remove-Item -Recurse -Force $Tmp } -} diff --git a/scripts/install.sh b/scripts/install.sh old mode 100644 new mode 100755 index fc403bf..726e548 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1,320 +1,29 @@ #!/usr/bin/env bash - -if [ -z "${BASH_VERSION:-}" ]; then - echo "This installer requires bash. Re-run with: curl -fsSL https://bloch-labs.com/install.sh | bash -s -- " >&2 - exit 1 -fi - set -euo pipefail -# Pretty output helpers -if [[ -t 1 && "${NO_COLOR:-}" != "1" ]]; then - RED="\033[31m"; GREEN="\033[32m"; YELLOW="\033[33m"; BLUE="\033[34m"; MAGENTA="\033[35m"; CYAN="\033[36m"; BOLD="\033[1m"; DIM="\033[2m"; RESET="\033[0m" -else - RED=""; GREEN=""; YELLOW=""; BLUE=""; MAGENTA=""; CYAN=""; BOLD=""; DIM=""; RESET="" -fi - -step() { printf "%b➜%b %s\n" "$BLUE" "$RESET" "$*"; } -success() { printf "%b✓%b %s\n" "$GREEN" "$RESET" "$*"; } -warn() { printf "%b!%b %s\n" "$YELLOW" "$RESET" "$*" >&2; } -error() { printf "%b✗%b %s\n" "$RED" "$RESET" "$*" >&2; } -note() { printf "%b%s%b\n" "$DIM" "$*" "$RESET"; } - -has_tty() { - # Consider interactive if stdout or stderr is a TTY, or FORCE_INTERACTIVE is set - [[ -t 1 || -t 2 || -n "${FORCE_INTERACTIVE:-}" ]] -} - -# Bloch installer for Linux/macOS -# Usage examples: -# curl -fsSL https://bloch-labs.com/install.sh | sh -s -- v1.0.0-rc.1 -# curl -fsSL https://bloch-labs.com/install.sh | sh -s -- latest -# INSTALL_DIR=$HOME/.local/bin sh scripts/install.sh v1.0.0-rc.1 - -REPO="bloch-labs/bloch" - -usage() { - cat < - -Environment variables: - INSTALL_DIR Destination directory (default: /usr/local/bin or ~/.local/bin fallback) - BLOCH_LIBRARY_DIR Override stdlib install root (default: platform data dir + /bloch/library) - -Examples: - $0 v1.0.0-rc.1 - $0 latest - INSTALL_DIR=\$HOME/.local/bin $0 v1.0.0-rc.1 -EOF -} - -if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then - usage - exit 0 +if (( $# > 1 )); then + echo "Usage: $0 [absolute-install-prefix]" >&2 + exit 2 fi -VERSION_INPUT=${1:-latest} - -require_cmd() { - command -v "$1" >/dev/null 2>&1 || { echo "Error: required command '$1' not found" >&2; exit 1; } -} - -require_cmd curl -require_cmd tar - -# Detect OS -UNAME_S=$(uname -s) -case "$UNAME_S" in - Linux) OS="Linux" ;; - Darwin) OS="macOS" ;; - *) echo "Error: unsupported OS: $UNAME_S" >&2; exit 1 ;; -esac - -# Detect ARCH mapping to GitHub runner arch naming -UNAME_M=$(uname -m) -case "$UNAME_M" in - x86_64|amd64) ARCH="X64" ;; - arm64|aarch64) ARCH="ARM64" ;; - *) echo "Error: unsupported architecture: $UNAME_M" >&2; exit 1 ;; +prefix="${1:-$HOME/.local}" +case "$prefix" in + /*) ;; + *) echo "The installation prefix must be an absolute path." >&2; exit 2 ;; esac -resolve_version() { - local input=$1 - if [[ "$input" == latest ]]; then - # Latest stable release (not prerelease) - local tag - tag=$(curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest" | sed -n 's/^ \{0,\}"tag_name": "\(.*\)",$/\1/p' | head -n1) - if [[ -z "$tag" ]]; then - echo "Error: could not resolve latest release tag via GitHub API" >&2 - exit 1 - fi - echo "$tag" - elif [[ "$input" == latest-rc ]]; then - # Latest prerelease; requires jq for robustness - if command -v jq >/dev/null 2>&1; then - curl -fsSL "https://api.github.com/repos/${REPO}/releases" | jq -r '.[] | select(.prerelease==true) | .tag_name' | head -n1 - else - echo "Error: resolving 'latest-rc' requires 'jq'. Please install jq or pass an explicit tag (e.g., v1.0.0-rc.1)." >&2 - exit 1 - fi - else - echo "$input" - fi -} - -TAG=$(resolve_version "$VERSION_INPUT") -if [[ -z "$TAG" ]]; then - echo "Error: empty tag resolved" >&2 - exit 1 -fi - -ASSET="bloch-${TAG}-${OS}-${ARCH}.tar.gz" -BASE_URL="https://github.com/${REPO}/releases/download/${TAG}" -ASSET_URL="${BASE_URL}/${ASSET}" -CHECKSUMS_URL="${BASE_URL}/checksums.txt" - -download_checksums() { - local url="$1" dest="$2" - if [[ -t 1 ]]; then - curl -fsSL -# "$url" -o "$dest" - else - curl -fsSL "$url" -o "$dest" - fi -} - -# Destination directory logic: prefer ~/.local/bin, then /usr/local/bin, then ~/bin -choose_dest() { - if [[ -n "${INSTALL_DIR:-}" ]]; then - echo "$INSTALL_DIR" - return - fi - # Prefer ~/.local/bin (create if possible) - if mkdir -p "$HOME/.local/bin" 2>/dev/null; then - if [[ -w "$HOME/.local/bin" ]]; then - echo "$HOME/.local/bin" - return - fi - fi - # Then /usr/local/bin if writable (no sudo) - if [[ -d "/usr/local/bin" && -w "/usr/local/bin" ]]; then - echo "/usr/local/bin" - return - fi - # Fallback to ~/bin (create if possible) - if mkdir -p "$HOME/bin" 2>/dev/null; then - echo "$HOME/bin" - return - fi - # Last resort - echo "$HOME/.local/bin" -} - -DEST=$(choose_dest) -mkdir -p "$DEST" - -TMPDIR=$(mktemp -d) -cleanup() { rm -rf "$TMPDIR"; } -trap cleanup EXIT - -step "Installing Bloch ${TAG} for ${OS}/${ARCH} into ${DEST}" -step "Downloading: ${ASSET_URL}" -if [[ -t 1 ]]; then - curl -fSL -# "$ASSET_URL" -o "$TMPDIR/$ASSET" -else - curl -fSL "$ASSET_URL" -o "$TMPDIR/$ASSET" -fi - -step "Downloading checksums: ${CHECKSUMS_URL}" -CHECKSUMS_PATH="" -if download_checksums "$CHECKSUMS_URL" "$TMPDIR/checksums.txt"; then - CHECKSUMS_PATH="$TMPDIR/checksums.txt" - CHECKSUMS_LABEL="checksums.txt" -else - warn "checksums.txt not found; trying OS/arch-specific checksum file" - ALT_CHECKSUMS_URL="${BASE_URL}/checksums-${OS}-${ARCH}.txt" - if download_checksums "$ALT_CHECKSUMS_URL" "$TMPDIR/checksums-${OS}-${ARCH}.txt"; then - CHECKSUMS_PATH="$TMPDIR/checksums-${OS}-${ARCH}.txt" - CHECKSUMS_LABEL="checksums-${OS}-${ARCH}.txt" - else - warn "No checksum file found; skipping verification" - NO_CHECKSUM=1 - fi -fi - -if [[ -z "${NO_CHECKSUM:-}" ]]; then - step "Verifying checksum (${CHECKSUMS_LABEL})" - if command -v sha256sum >/dev/null 2>&1; then - EXPECTED=$(grep -F " ${ASSET}" "$CHECKSUMS_PATH" | awk '{print $1}') - ACTUAL=$(sha256sum "$TMPDIR/$ASSET" | awk '{print $1}') - else - EXPECTED=$(grep -F " ${ASSET}" "$CHECKSUMS_PATH" | awk '{print $1}') - ACTUAL=$(shasum -a 256 "$TMPDIR/$ASSET" | awk '{print $1}') - fi - if [[ -z "${EXPECTED:-}" ]]; then - warn "expected checksum not found for ${ASSET} in ${CHECKSUMS_LABEL}; skipping verification" - elif [[ "$EXPECTED" != "$ACTUAL" ]]; then - error "checksum mismatch for ${ASSET}" - echo "Expected: $EXPECTED" >&2 - echo "Actual: $ACTUAL" >&2 - exit 1 - else - success "Checksum OK" - fi -fi - -step "Extracting" -tar -C "$TMPDIR" -xzf "$TMPDIR/$ASSET" - -BLOCH_BIN_CANDIDATES=$(find "$TMPDIR" -maxdepth 5 -type f -name 'bloch') -if [[ -z "${BLOCH_BIN_CANDIDATES// }" ]]; then - error "extracted archive did not contain a 'bloch' binary" - exit 1 -fi - -candidate_count=$(printf "%s\n" "$BLOCH_BIN_CANDIDATES" | sed '/^$/d' | wc -l | tr -d '[:space:]') -if [[ "$candidate_count" != "1" ]]; then - warn "Multiple bloch binaries found; using the first match" -fi -BLOCH_BIN=$(printf "%s\n" "$BLOCH_BIN_CANDIDATES" | sed '/^$/d' | head -n1) - -chmod +x "$BLOCH_BIN" -if ! BLOCH_PROBE_OUTPUT=$("$BLOCH_BIN" --version 2>&1); then - error "Downloaded binary failed to run on this system." - if [[ "$BLOCH_PROBE_OUTPUT" == *"GLIBC_"* || "$BLOCH_PROBE_OUTPUT" == *"GLIBCXX_"* ]]; then - warn "Bloch requires glibc >= 2.35 and libstdc++ >= 3.4.30." - warn "Upgrade to a newer Linux distribution or build from source." - fi - echo "$BLOCH_PROBE_OUTPUT" >&2 - exit 1 -fi -install -m 0755 "$BLOCH_BIN" "$DEST/bloch" - -success "Installed: $DEST/bloch" -note "You can verify with: bloch --version" - -STDLIB_SRC=$(find "$TMPDIR" -type d -path '*/share/bloch/library' | head -n1 || true) -if [[ -n "${STDLIB_SRC:-}" ]]; then - if [[ -n "${BLOCH_LIBRARY_DIR:-}" ]]; then - LIB_ROOT="$BLOCH_LIBRARY_DIR" - elif [[ "$OS" == "macOS" ]]; then - LIB_ROOT="$HOME/Library/Application Support/Bloch/library" - else - DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}" - LIB_ROOT="$DATA_HOME/bloch/library" - fi - - VERSION_ROOT="$LIB_ROOT/$TAG" - mkdir -p "$LIB_ROOT" "$VERSION_ROOT" - cp -R "$STDLIB_SRC/." "$LIB_ROOT/" - cp -R "$STDLIB_SRC/." "$VERSION_ROOT/" - success "Installed stdlib: $VERSION_ROOT" -else - warn "Bundled stdlib not found in archive; falling back to runtime built-ins only" -fi - -# Offer to add DEST to PATH if not already there -path_has_dest=0 -case ":$PATH:" in - *":$DEST:"*) path_has_dest=1 ;; -esac - -if ! command -v bloch >/dev/null 2>&1 || [[ $path_has_dest -eq 0 ]]; then - SHELL_NAME=$(basename "${SHELL:-}") - if [[ "$SHELL_NAME" == "fish" ]]; then - warn "Detected fish shell. Automatic PATH update not applied." - echo "Add this line to ~/.config/fish/config.fish:" >&2 - echo " set -gx PATH \"$DEST\" \$PATH" >&2 - else - # Choose a profile file - PROFILE="" - if [[ "$SHELL_NAME" == "zsh" ]]; then - PROFILE="$HOME/.zshrc" - # Prefer .zprofile for login shells if it exists - [[ -f "$HOME/.zprofile" ]] && PROFILE="$HOME/.zprofile" - elif [[ "$SHELL_NAME" == "bash" ]]; then - if [[ "$OS" == "macOS" ]]; then - PROFILE=${HOME}/.bash_profile - else - PROFILE=${HOME}/.bashrc - fi - fi - # Fallback - [[ -z "$PROFILE" ]] && PROFILE="$HOME/.profile" - - step "Adding $DEST to PATH via $(basename "$PROFILE")" - mkdir -p "$(dirname "$PROFILE")" || true - if [[ -w "$(dirname "$PROFILE")" ]] || [[ ! -e "$PROFILE" ]]; then - # Append only if not already present - if ! grep -Fq "$DEST" "$PROFILE" 2>/dev/null; then - printf "\n# Added by Bloch installer\nexport PATH=\"%s:\$PATH\"\n" "$DEST" >> "$PROFILE" 2>/dev/null || { - warn "Could not write to $(basename "$PROFILE")." - echo "Add to your shell profile manually: export PATH=\"$DEST:\$PATH\"" >&2 - } - success "Updated $(basename "$PROFILE"): added $DEST to PATH" - # Best-effort: export into this process for immediate use - export PATH="$DEST:$PATH" - # If running bash and profile is bash-compatible, source it for this subshell - if [[ "$SHELL_NAME" == "bash" ]] && [[ "$(basename "$PROFILE")" =~ ^(\.bashrc|\.bash_profile|\.profile)$ ]]; then - step "Refreshing current shell environment" - # shellcheck disable=SC1090 - . "$PROFILE" 2>/dev/null || true - hash -r 2>/dev/null || true - fi - # Advise user how to refresh their parent shell - if [[ "$SHELL_NAME" == "zsh" ]]; then - note "Open a new terminal or run: exec zsh -l (or 'rehash')" - else - note "Open a new terminal or run: exec $SHELL -l" - fi - else - note "PATH already contains $DEST in $(basename "$PROFILE")" - fi - else - warn "No write permission for $(dirname "$PROFILE")." - echo "Add to your shell profile manually: export PATH=\"$DEST:\$PATH\"" >&2 - fi - fi -fi +for tool in cmake ninja; do + command -v "$tool" >/dev/null 2>&1 || { + echo "Missing prerequisite: $tool" >&2 + exit 1 + } +done + +cd "$(dirname "${BASH_SOURCE[0]}")/.." +cmake --preset release +cmake --build --preset release --parallel 2 +ctest --preset release +cmake --install build/release --prefix "$prefix" + +"$prefix/bin/basis" --version +printf '\nInstalled Basis to %s/bin/basis\nAdd %s/bin to your PATH.\n' "$prefix" "$prefix" diff --git a/scripts/run_examples.sh b/scripts/run_examples.sh index 359928e..2491edf 100755 --- a/scripts/run_examples.sh +++ b/scripts/run_examples.sh @@ -23,12 +23,12 @@ fi SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" -BLOCH_BIN="${1:-${BUILD_DIR:-${ROOT_DIR}/build}/bin/bloch}" +BLOCH_BIN="${1:-${BUILD_DIR:-${ROOT_DIR}/build}/bin/basis}" EXAMPLE_TIMEOUT_SECONDS="${EXAMPLE_TIMEOUT_SECONDS:-30}" if [[ ! -x "${BLOCH_BIN}" ]]; then - echo "Bloch executable not found or not executable: ${BLOCH_BIN}" >&2 - echo "Build Bloch first or pass the executable path as the first argument." >&2 + echo "Basis executable not found or not executable: ${BLOCH_BIN}" >&2 + echo "Build Basis first or pass the executable path as the first argument." >&2 exit 1 fi if [[ ! "${EXAMPLE_TIMEOUT_SECONDS}" =~ ^[1-9][0-9]*$ ]]; then diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 97a2aa2..eaf3932 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,105 +1,134 @@ -# Prefer static OpenSSL to avoid a runtime dependency; fall back to shared if -# static libraries are unavailable. Release artifacts can force static by -# ensuring libssl.a/libcrypto.a are present. -set(OpenSSL_USE_STATIC_LIBS ON) -find_package(OpenSSL QUIET) -if(NOT OpenSSL_FOUND) - set(OpenSSL_USE_STATIC_LIBS OFF) - find_package(OpenSSL REQUIRED) -endif() +find_package(Threads REQUIRED) -# --------------------------------------------------------------------------- -# Source layout by responsibility (compiler / runtime / cli / updater) -# --------------------------------------------------------------------------- -set(BLOCH_COMPILER_SOURCES - ${CMAKE_CURRENT_SOURCE_DIR}/bloch/compiler/import/module_loader.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/bloch/compiler/lexer/lexer.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/bloch/compiler/parser/parser.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/bloch/compiler/semantics/built_ins.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/bloch/compiler/semantics/semantic_analyser.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/bloch/compiler/semantics/type_system.cpp +add_library( + bloch_compiler + STATIC + bloch/compiler/import/module_loader.cpp + bloch/compiler/lexer/lexer.cpp + bloch/compiler/parser/parser.cpp + bloch/compiler/semantics/built_ins.cpp + bloch/compiler/semantics/semantic_analyser.cpp + bloch/compiler/semantics/type_system.cpp ) -set(BLOCH_RUNTIME_SOURCES - ${CMAKE_CURRENT_SOURCE_DIR}/bloch/runtime/qasm_simulator.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/bloch/runtime/runtime_evaluator.cpp +add_library(bloch::compiler ALIAS bloch_compiler) + +target_compile_features( + bloch_compiler + PUBLIC + cxx_std_20 ) -set(BLOCH_CLI_SOURCES - ${CMAKE_CURRENT_SOURCE_DIR}/bloch/cli/cli.cpp +target_include_directories( + bloch_compiler + PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}" ) -set(BLOCH_UPDATE_SOURCES - ${CMAKE_CURRENT_SOURCE_DIR}/bloch/update/update_manager.cpp +target_link_libraries( + bloch_compiler + PRIVATE + bloch::project_warnings ) -set(BLOCH_HTTP_SOURCES - ${CMAKE_CURRENT_SOURCE_DIR}/bloch/http/http_client.cpp +add_library( + bloch_runtime + STATIC + bloch/runtime/qasm_simulator.cpp + bloch/runtime/runtime_evaluator.cpp ) -# Shared headers and compile flags that are safe across all components. -add_library(bloch_support INTERFACE) -target_include_directories(bloch_support INTERFACE - ${CMAKE_CURRENT_SOURCE_DIR} +add_library(bloch::runtime ALIAS bloch_runtime) + +target_compile_features( + bloch_runtime + PUBLIC + cxx_std_20 ) -add_library(bloch_compiler ${BLOCH_COMPILER_SOURCES}) -target_link_libraries(bloch_compiler - PUBLIC bloch_support +target_include_directories( + bloch_runtime + PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}" ) -add_library(bloch_runtime ${BLOCH_RUNTIME_SOURCES}) -target_link_libraries(bloch_runtime - PUBLIC bloch_compiler bloch_support +target_link_libraries( + bloch_runtime + PUBLIC + bloch::compiler + Threads::Threads + PRIVATE + bloch::project_warnings ) -add_library(bloch_update ${BLOCH_UPDATE_SOURCES}) -target_link_libraries(bloch_update - PUBLIC bloch_support OpenSSL::SSL OpenSSL::Crypto +add_library( + bloch_cli + STATIC + bloch/cli/cli.cpp ) -target_compile_definitions(bloch_update PRIVATE CPPHTTPLIB_OPENSSL_SUPPORT) -add_library(bloch_http ${BLOCH_HTTP_SOURCES}) -target_link_libraries(bloch_http - PUBLIC bloch_support +add_library(bloch::cli ALIAS bloch_cli) + +target_compile_features( + bloch_cli + PUBLIC + cxx_std_20 ) -add_library(bloch_cli ${BLOCH_CLI_SOURCES}) -target_link_libraries(bloch_cli - PUBLIC bloch_runtime bloch_update bloch_support +target_include_directories( + bloch_cli + PUBLIC + "${CMAKE_CURRENT_SOURCE_DIR}" ) -target_compile_definitions(bloch_cli PUBLIC - BLOCH_VERSION="${BLOCH_VERSION}" - BLOCH_COMMIT_HASH="${BLOCH_COMMIT_HASH}" +target_link_libraries( + bloch_cli + PUBLIC + bloch::runtime + PRIVATE + bloch::project_warnings ) -add_executable(bloch +add_executable( + basis main.cpp ) -target_link_libraries(bloch - PRIVATE bloch_cli +target_compile_features( + basis + PRIVATE + cxx_std_20 ) -# Install targets for local development installs -install(TARGETS bloch bloch_cli bloch_compiler bloch_runtime bloch_update bloch_http - RUNTIME DESTINATION bin - LIBRARY DESTINATION lib - ARCHIVE DESTINATION lib +target_link_libraries( + basis + PRIVATE + bloch::cli + bloch::project_warnings ) -install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/bloch - DESTINATION include - FILES_MATCHING PATTERN "*.hpp" +set_target_properties( + bloch_compiler + bloch_runtime + bloch_cli + basis + PROPERTIES + CXX_EXTENSIONS OFF ) -install(DIRECTORY ${CMAKE_SOURCE_DIR}/library/ - DESTINATION share/bloch/library - OPTIONAL +set_target_properties( + basis + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin" +) + +target_compile_definitions(bloch_cli PUBLIC + BLOCH_VERSION="${BASIS_VERSION}" + BLOCH_COMMIT_HASH="${BASIS_COMMIT}" ) -install(DIRECTORY ${CMAKE_SOURCE_DIR}/stdlib/ - DESTINATION share/bloch/stdlib - OPTIONAL +install(TARGETS basis RUNTIME DESTINATION bin) +install(DIRECTORY "${PROJECT_SOURCE_DIR}/library/" + DESTINATION "share/basis/library" + FILES_MATCHING PATTERN "*.bloch" ) diff --git a/src/bloch/cli/cli.cpp b/src/bloch/cli/cli.cpp index 9812406..7be59d1 100644 --- a/src/bloch/cli/cli.cpp +++ b/src/bloch/cli/cli.cpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -33,346 +33,342 @@ #include "bloch/compiler/semantics/semantic_analyser.hpp" #include "bloch/runtime/runtime_evaluator.hpp" #include "bloch/support/error/bloch_error.hpp" -#include "bloch/update/update_manager.hpp" namespace bloch::cli { - namespace { - namespace fs = std::filesystem; - - struct CliOption { - std::string_view flag; - std::string_view arg; - std::string_view description; - }; - - static constexpr std::string_view kFlagHelp = "--help"; - static constexpr std::string_view kFlagVersion = "--version"; - static constexpr std::string_view kFlagEmitQasm = "--emit-qasm"; - static constexpr std::string_view kFlagShotsPrefix = "--shots="; - static constexpr std::string_view kFlagEchoPrefix = "--echo="; - static constexpr std::string_view kFlagUpdate = "--update"; - - static constexpr std::array kCliOptions = { - CliOption{kFlagHelp, "", "Show this help and exit"}, - CliOption{kFlagVersion, "", "Print version and exit (checks for newer releases)"}, - CliOption{kFlagEmitQasm, "", "Print emitted QASM to stdout"}, - CliOption{ - "--shots", "=N", - "Run the program N times and aggregate @tracked counts (deprecated in v2.0.0; " - "prefer @shots(N))"}, - CliOption{"--echo", "=auto|all|none", - "Control echo statements (default: auto; suppress when taking many shots)"}, - CliOption{kFlagUpdate, "", "Download and install the latest release"}, - }; - - std::string formattedVersion(const Context& ctx) { - constexpr std::string_view unknown = "unknown"; - if (ctx.commit == unknown || ctx.commit.empty()) { - return std::string(ctx.version); - } - return std::string(ctx.version) + " (" + std::string(ctx.commit) + ")"; - } - - void printHelp(const Context& ctx) { - size_t width = 0; - for (const auto& opt : kCliOptions) { - width = std::max(width, opt.flag.size() + opt.arg.size()); - } - std::cout << "Bloch " << formattedVersion(ctx) << "\n" - << "Usage: bloch [options] \n\n" - << "Options:\n"; - for (const auto& opt : kCliOptions) { - std::ostringstream line; - line << " " << opt.flag << opt.arg; - std::cout << std::left << std::setw(static_cast(width + 4)) << line.str() - << opt.description << "\n"; - } - std::cout << "\nBehaviour:\n" - << " - Writes .qasm alongside the input file.\n" - << " - When --shots is used, prints an aggregate table of tracked values.\n" - << std::endl; - } - - void printVersion(const Context& ctx) { std::cout << formattedVersion(ctx) << std::endl; } - - std::string normaliseVersion(std::string_view version) { - std::string v(version); - if (!v.empty() && v.front() == 'v') - v.erase(v.begin()); - return v; - } - - void addPathCandidate(std::vector& paths, const fs::path& candidate) { - if (candidate.empty()) - return; +namespace { +namespace fs = std::filesystem; + +struct CliOption { + std::string_view flag; + std::string_view arg; + std::string_view description; +}; + +static constexpr std::string_view kFlagHelp = "--help"; +static constexpr std::string_view kFlagVersion = "--version"; +static constexpr std::string_view kFlagEmitQasm = "--emit-qasm"; +static constexpr std::string_view kFlagShotsPrefix = "--shots="; +static constexpr std::string_view kFlagEchoPrefix = "--echo="; + +static constexpr std::array kCliOptions = { + CliOption{kFlagHelp, "", "Show this help and exit"}, + CliOption{kFlagVersion, "", "Print version and exit"}, + CliOption{kFlagEmitQasm, "", "Print emitted QASM to stdout"}, + CliOption{"--shots", "=N", "Run the program N times and aggregate @tracked counts"}, + CliOption{"--echo", "=auto|all|none", + "Control echo statements (default: auto; suppress when taking many shots)"}, +}; + +std::string formattedVersion(const Context& ctx) { + constexpr std::string_view unknown = "unknown"; + if (ctx.commit == unknown || ctx.commit.empty()) { + return std::string(ctx.version); + } + return std::string(ctx.version) + " (" + std::string(ctx.commit) + ")"; +} + +void printHelp(const Context& ctx) { + size_t width = 0; + for (const auto& opt : kCliOptions) { + width = std::max(width, opt.flag.size() + opt.arg.size()); + } + std::cout << "Basis " << formattedVersion(ctx) << "\n" + << "Usage: basis [options] \n\n" + << "Options:\n"; + for (const auto& opt : kCliOptions) { + std::ostringstream line; + line << " " << opt.flag << opt.arg; + std::cout << std::left << std::setw(static_cast(width + 4)) << line.str() + << opt.description << "\n"; + } + std::cout << "\nBehaviour:\n" + << " - Writes .qasm alongside the input file.\n" + << " - When --shots is used, prints an aggregate table of tracked values.\n" + << std::endl; +} + +void printVersion(const Context& ctx) { std::cout << formattedVersion(ctx) << std::endl; } + +std::string normaliseVersion(std::string_view version) { + std::string v(version); + if (!v.empty() && v.front() == 'v') + v.erase(v.begin()); + return v; +} + +void addPathCandidate(std::vector& paths, const fs::path& candidate) { + if (candidate.empty()) + return; + std::error_code ec; + fs::path canonical = fs::weakly_canonical(candidate, ec); + std::string normalised = (ec ? candidate.lexically_normal() : canonical).string(); + if (normalised.empty()) + return; + if (std::find(paths.begin(), paths.end(), normalised) == paths.end()) + paths.push_back(normalised); +} + +void addVersionedRoots(std::vector& paths, const fs::path& root, + const std::string& version) { + if (root.empty()) + return; + if (!version.empty()) { + addPathCandidate(paths, root / version); + addPathCandidate(paths, root / ("v" + version)); + } + addPathCandidate(paths, root); +} + +fs::path resolveExecutablePath(const char* argv0) { + fs::path executable(argv0); + if (!executable.has_parent_path()) { + const char* path = std::getenv("PATH"); + std::istringstream entries(path ? path : ""); + std::string entry; +#if defined(_WIN32) + constexpr char separator = ';'; +#else + constexpr char separator = ':'; +#endif + while (std::getline(entries, entry, separator)) { std::error_code ec; - fs::path canonical = fs::weakly_canonical(candidate, ec); - std::string normalised = (ec ? candidate.lexically_normal() : canonical).string(); - if (normalised.empty()) - return; - if (std::find(paths.begin(), paths.end(), normalised) == paths.end()) - paths.push_back(normalised); - } - - void addVersionedRoots(std::vector& paths, const fs::path& root, - const std::string& version) { - if (root.empty()) - return; - if (!version.empty()) { - addPathCandidate(paths, root / version); - addPathCandidate(paths, root / ("v" + version)); + fs::path candidate = fs::path(entry) / executable; + if (fs::is_regular_file(candidate, ec)) { + executable = candidate; + break; } - addPathCandidate(paths, root); } - - std::vector resolveStdlibSearchPaths(const Context& ctx, const char* argv0) { - std::vector paths; - std::string version = normaliseVersion(ctx.version); - - if (const char* overridePath = std::getenv("BLOCH_STDLIB_PATH"); - overridePath && *overridePath) { - addVersionedRoots(paths, fs::path(overridePath), version); - } else { + } + std::error_code ec; + fs::path resolved = fs::weakly_canonical(executable, ec); + return ec ? executable : resolved; +} + +std::vector resolveStdlibSearchPaths(const Context& ctx, const char* argv0) { + std::vector paths; + std::string version = normaliseVersion(ctx.version); + + if (const char* overridePath = std::getenv("BASIS_STDLIB_PATH"); + overridePath && *overridePath) { + addVersionedRoots(paths, fs::path(overridePath), version); + } else { #if defined(_WIN32) - if (const char* localAppData = std::getenv("LOCALAPPDATA"); - localAppData && *localAppData) { - addVersionedRoots(paths, fs::path(localAppData) / "Bloch" / "library", version); - } + if (const char* localAppData = std::getenv("LOCALAPPDATA"); localAppData && *localAppData) { + addVersionedRoots(paths, fs::path(localAppData) / "Basis" / "library", version); + } #elif defined(__APPLE__) - if (const char* home = std::getenv("HOME"); home && *home) { - addVersionedRoots( - paths, - fs::path(home) / "Library" / "Application Support" / "Bloch" / "library", - version); - } + if (const char* home = std::getenv("HOME"); home && *home) { + addVersionedRoots( + paths, fs::path(home) / "Library" / "Application Support" / "Basis" / "library", + version); + } #else - fs::path dataRoot; - if (const char* xdgDataHome = std::getenv("XDG_DATA_HOME"); - xdgDataHome && *xdgDataHome) { - dataRoot = fs::path(xdgDataHome); - } else if (const char* home = std::getenv("HOME"); home && *home) { - dataRoot = fs::path(home) / ".local" / "share"; - } - if (!dataRoot.empty()) - addVersionedRoots(paths, dataRoot / "bloch" / "library", version); + fs::path dataRoot; + if (const char* xdgDataHome = std::getenv("XDG_DATA_HOME"); xdgDataHome && *xdgDataHome) { + dataRoot = fs::path(xdgDataHome); + } else if (const char* home = std::getenv("HOME"); home && *home) { + dataRoot = fs::path(home) / ".local" / "share"; + } + if (!dataRoot.empty()) + addVersionedRoots(paths, dataRoot / "basis" / "library", version); #endif + } + + if (argv0 && *argv0) { + fs::path exePath = resolveExecutablePath(argv0); + if (!exePath.empty()) { + fs::path shareRoot = exePath.parent_path() / ".." / "share" / "basis"; + addVersionedRoots(paths, shareRoot / "library", version); + addPathCandidate(paths, shareRoot / "stdlib"); + // Development checkout fallbacks. + addPathCandidate(paths, exePath.parent_path() / ".." / ".." / "library"); + addPathCandidate(paths, exePath.parent_path() / ".." / ".." / ".." / "library"); + } + } + + addPathCandidate(paths, fs::current_path() / "library"); + addPathCandidate(paths, fs::current_path() / "stdlib"); + + return paths; +} + +int runImpl(int argc, char** argv, const Context& ctx) { + if (argc < 2) { + std::cerr << "Usage: basis [options] (use --help for details)\n"; + return 1; + } + + bool emitQasm = false; + int shots = 1; + bool shotsProvided = false; + bool isCliShots = false; + int cliShots = 1; + std::string echoOpt; + std::string file; + + for (int i = 1; i < argc; ++i) { + std::string arg = argv[i]; + if (arg == kFlagHelp) { + printHelp(ctx); + return 0; + } else if (arg == kFlagVersion) { + printVersion(ctx); + return 0; + } else if (arg == kFlagEmitQasm) { + emitQasm = true; + } else if (arg.rfind(kFlagShotsPrefix, 0) == 0) { + isCliShots = true; + cliShots = std::stoi(arg.substr(kFlagShotsPrefix.size())); + if (cliShots <= 0) { + std::cerr << "--shots must be positive\n"; + return 1; } - - if (argv0 && *argv0) { - std::error_code ec; - fs::path exePath = fs::weakly_canonical(fs::path(argv0), ec); - if (ec) - exePath = fs::absolute(fs::path(argv0), ec); - if (!exePath.empty()) { - fs::path shareRoot = exePath.parent_path() / ".." / "share" / "bloch"; - addVersionedRoots(paths, shareRoot / "library", version); - addPathCandidate(paths, shareRoot / "stdlib"); - // Development tree fallback (e.g. ./build/bin/bloch from source checkout). - addPathCandidate(paths, exePath.parent_path() / ".." / ".." / "library"); - } + } else if (arg.rfind(kFlagEchoPrefix, 0) == 0) { + echoOpt = arg.substr(kFlagEchoPrefix.size()); + } else { + file = arg; + } + } + if (file.empty()) { + std::cerr << "No input file provided (use --help for usage)\n"; + return 1; + } + + try { + auto stdlibPaths = resolveStdlibSearchPaths(ctx, argc > 0 ? argv[0] : nullptr); + bloch::compiler::ModuleLoader loader(stdlibPaths); + std::unique_ptr program = loader.load(file); + bool isAnnotationShots = program->shots.first; + + if (isCliShots && !isAnnotationShots) { + shotsProvided = true; + shots = cliShots; + } else if (!isCliShots && isAnnotationShots) { + shotsProvided = true; + shots = program->shots.second; + } else if (isCliShots && isAnnotationShots) { + shotsProvided = true; + shots = program->shots.second; + if (cliShots != shots) { + bloch::support::blochWarning( + 0, 0, + "The '--shots=N' flag differs from your @shots(N) annotation. Ignoring " + "CLI flag and using annotation value."); } - - addPathCandidate(paths, fs::current_path() / "library"); - addPathCandidate(paths, fs::current_path() / "stdlib"); - - return paths; } - int runImpl(int argc, char** argv, const Context& ctx) { - const std::string version(ctx.version); - if (argc < 2) { - std::cerr << "Usage: bloch [options] (use --help for details)\n"; - return 1; + // By default we suppress echo when taking many shots, unless the user + // explicitly asks for it via --echo=all. + bool echoAll = echoOpt.empty() ? (!shotsProvided || shots == 1) : (echoOpt == "all"); + if (shotsProvided && shots > 1 && echoOpt.empty()) + bloch::support::blochInfo(0, 0, "suppressing echo; to view them use --echo=all"); + + bloch::compiler::SemanticAnalyser analyser; + analyser.analyse(*program); + std::string qasm; + if (shotsProvided) { + // Multi-shot execution: aggregate tracked values and report a summary. + std::unordered_map> aggregate; + auto start = std::chrono::steady_clock::now(); + for (int s = 0; s < shots; ++s) { + bloch::runtime::RuntimeEvaluator evaluator(s == shots - 1); + evaluator.setEcho(echoAll); + // Suppress per-shot warnings; only show for last shot + if (s < shots - 1) + evaluator.setWarnOnExit(false); + evaluator.execute(*program); + if (s == shots - 1) + qasm = evaluator.getQasm(); + for (const auto& vk : evaluator.trackedCounts()) + for (const auto& vv : vk.second) + aggregate[vk.first][vv.first] += vv.second; } - - bool emitQasm = false; - int shots = 1; - bool shotsProvided = false; - bool isCliShots = false; - int cliShots = 1; - std::string echoOpt; - std::string file; - - for (int i = 1; i < argc; ++i) { - std::string arg = argv[i]; - if (arg == kFlagHelp) { - printHelp(ctx); - return 0; - } else if (arg == kFlagVersion) { - printVersion(ctx); - bloch::update::checkForUpdatesIfDue(version); - return 0; - } else if (arg == kFlagUpdate) { - return bloch::update::performSelfUpdate(version, argv[0]) ? 0 : 1; - } else if (arg == kFlagEmitQasm) { - emitQasm = true; - } else if (arg.rfind(kFlagShotsPrefix, 0) == 0) { - isCliShots = true; - cliShots = std::stoi(arg.substr(kFlagShotsPrefix.size())); - if (cliShots <= 0) { - std::cerr << "--shots must be positive\n"; - return 1; + auto end = std::chrono::steady_clock::now(); + double elapsed = + std::chrono::duration_cast>(end - start).count(); + std::string base = file.substr(0, file.find_last_of('.')); + std::ofstream qfile(base + ".qasm"); + qfile << qasm; + qfile.close(); + + // Warn if nothing was tracked, but still print run header and timing + if (aggregate.empty()) + bloch::support::blochWarning( + 0, 0, "No tracked variables. Use @tracked to collect statistics."); + + std::cout << "Shots: " << shots << "\n"; + std::cout << "Backend: Basis Ideal Simulator\n"; + std::cout << std::fixed << std::setprecision(3); + std::cout << "Elapsed: " << elapsed << "s\n\n"; + + if (!aggregate.empty()) { + for (auto& var : aggregate) { + // Header: e.g., "qubit q" or "qubit[] qreg" + std::cout << var.first << "\n"; + std::vector> vals(var.second.begin(), + var.second.end()); + auto isBinary = [](const std::string& s) { + return !s.empty() && s.find_first_not_of("01") == std::string::npos; + }; + std::stable_sort(vals.begin(), vals.end(), [&](const auto& a, const auto& b) { + bool ab = isBinary(a.first); + bool bb = isBinary(b.first); + if (ab != bb) + return ab; // binary outcomes first; e.g., place '?' at end + if (!ab && !bb) + return a.first < b.first; + // Both binary: compare as integers, prefer shorter width first + if (a.first.size() != b.first.size()) + return a.first.size() < b.first.size(); + return std::stoi(a.first, nullptr, 2) < std::stoi(b.first, nullptr, 2); + }); + // Dynamic column sizing for outcome strings + size_t outcomeWidth = 7; + for (const auto& p : vals) + outcomeWidth = std::max(outcomeWidth, p.first.size()); + std::cout << std::left << std::setw(static_cast(outcomeWidth)) << "outcome" + << " | " << std::right << std::setw(5) << "count" << " | " + << std::setw(5) << "prob" << "\n"; + std::cout << std::string(outcomeWidth, '-') << "-+-------+-----\n"; + for (auto& p : vals) { + double prob = static_cast(p.second) / shots; + std::cout << std::left << std::setw(static_cast(outcomeWidth)) + << p.first << " | " << std::right << std::setw(5) << p.second + << " | " << std::setw(5) << prob << "\n"; } - } else if (arg.rfind(kFlagEchoPrefix, 0) == 0) { - echoOpt = arg.substr(kFlagEchoPrefix.size()); - } else { - file = arg; + std::cout << "\n"; } } - if (file.empty()) { - std::cerr << "No input file provided (use --help for usage)\n"; - return 1; + if (emitQasm) { + std::cout << qasm; + return 0; } - - // Run a non-blocking update check at most once every 72 hours. - bloch::update::checkForUpdatesIfDue(version); - - try { - auto stdlibPaths = resolveStdlibSearchPaths(ctx, argc > 0 ? argv[0] : nullptr); - bloch::compiler::ModuleLoader loader(stdlibPaths); - std::unique_ptr program = loader.load(file); - bool isAnnotationShots = program->shots.first; - - if (isCliShots && !isAnnotationShots) { - shotsProvided = true; - shots = cliShots; - bloch::support::blochWarning( - 0, 0, - "The '--shots=N' flag will be deprecated in v2.0.0. Please decorate your " - "main() function with the @shots(N) annotation instead."); - } else if (!isCliShots && isAnnotationShots) { - shotsProvided = true; - shots = program->shots.second; - } else if (isCliShots && isAnnotationShots) { - shotsProvided = true; - shots = program->shots.second; - if (cliShots != shots) { - bloch::support::blochWarning( - 0, 0, - "The '--shots=N' flag differs from your @shots(N) annotation. Ignoring " - "CLI flag and using annotation value."); - } - } - - // By default we suppress echo when taking many shots, unless the user - // explicitly asks for it via --echo=all. - bool echoAll = - echoOpt.empty() ? (!shotsProvided || shots == 1) : (echoOpt == "all"); - if (shotsProvided && shots > 1 && echoOpt.empty()) - bloch::support::blochInfo(0, 0, - "suppressing echo; to view them use --echo=all"); - - bloch::compiler::SemanticAnalyser analyser; - analyser.analyse(*program); - std::string qasm; - if (shotsProvided) { - // Multi-shot execution: aggregate tracked values and report a summary. - std::unordered_map> aggregate; - auto start = std::chrono::steady_clock::now(); - for (int s = 0; s < shots; ++s) { - bloch::runtime::RuntimeEvaluator evaluator(s == shots - 1); - evaluator.setEcho(echoAll); - // Suppress per-shot warnings; only show for last shot - if (s < shots - 1) - evaluator.setWarnOnExit(false); - evaluator.execute(*program); - if (s == shots - 1) - qasm = evaluator.getQasm(); - for (const auto& vk : evaluator.trackedCounts()) - for (const auto& vv : vk.second) - aggregate[vk.first][vv.first] += vv.second; - } - auto end = std::chrono::steady_clock::now(); - double elapsed = - std::chrono::duration_cast>(end - start) - .count(); - std::string base = file.substr(0, file.find_last_of('.')); - std::ofstream qfile(base + ".qasm"); - qfile << qasm; - qfile.close(); - - // Warn if nothing was tracked, but still print run header and timing - if (aggregate.empty()) - bloch::support::blochWarning( - 0, 0, "No tracked variables. Use @tracked to collect statistics."); - - std::cout << "Shots: " << shots << "\n"; - std::cout << "Backend: Bloch Ideal Simulator\n"; - std::cout << std::fixed << std::setprecision(3); - std::cout << "Elapsed: " << elapsed << "s\n\n"; - - if (!aggregate.empty()) { - for (auto& var : aggregate) { - // Header: e.g., "qubit q" or "qubit[] qreg" - std::cout << var.first << "\n"; - std::vector> vals(var.second.begin(), - var.second.end()); - auto isBinary = [](const std::string& s) { - return !s.empty() && s.find_first_not_of("01") == std::string::npos; - }; - std::stable_sort( - vals.begin(), vals.end(), [&](const auto& a, const auto& b) { - bool ab = isBinary(a.first); - bool bb = isBinary(b.first); - if (ab != bb) - return ab; // binary outcomes first; e.g., place '?' at end - if (!ab && !bb) - return a.first < b.first; - // Both binary: compare as integers, prefer shorter width first - if (a.first.size() != b.first.size()) - return a.first.size() < b.first.size(); - return std::stoi(a.first, nullptr, 2) < - std::stoi(b.first, nullptr, 2); - }); - // Dynamic column sizing for outcome strings - size_t outcomeWidth = 7; - for (const auto& p : vals) - outcomeWidth = std::max(outcomeWidth, p.first.size()); - std::cout << std::left << std::setw(static_cast(outcomeWidth)) - << "outcome" - << " | " << std::right << std::setw(5) << "count" - << " | " << std::setw(5) << "prob" - << "\n"; - std::cout << std::string(outcomeWidth, '-') << "-+-------+-----\n"; - for (auto& p : vals) { - double prob = static_cast(p.second) / shots; - std::cout << std::left << std::setw(static_cast(outcomeWidth)) - << p.first << " | " << std::right << std::setw(5) - << p.second << " | " << std::setw(5) << prob << "\n"; - } - std::cout << "\n"; - } - } - if (emitQasm) { - std::cout << qasm; - return 0; - } - } else { - bloch::runtime::RuntimeEvaluator evaluator; - evaluator.setEcho(echoAll); - evaluator.execute(*program); - qasm = evaluator.getQasm(); - std::string base = file.substr(0, file.find_last_of('.')); - std::ofstream qfile(base + ".qasm"); - qfile << qasm; - qfile.close(); - if (emitQasm) { - std::cout << qasm; - return 0; - } - } - } catch (const std::exception& ex) { - // Print a clear stop message, then the actual error - std::cerr << bloch::support::format(bloch::support::MessageLevel::Error, 0, 0, - "Stopping program execution..."); - std::cerr << ex.what() << std::endl; - return 1; + } else { + bloch::runtime::RuntimeEvaluator evaluator; + evaluator.setEcho(echoAll); + evaluator.execute(*program); + qasm = evaluator.getQasm(); + std::string base = file.substr(0, file.find_last_of('.')); + std::ofstream qfile(base + ".qasm"); + qfile << qasm; + qfile.close(); + if (emitQasm) { + std::cout << qasm; + return 0; } - return 0; } - - } // namespace - - int run(int argc, char** argv, const Context& ctx) { return runImpl(argc, argv, ctx); } + } catch (const std::exception& ex) { + // Print a clear stop message, then the actual error + std::cerr << bloch::support::format(bloch::support::MessageLevel::Error, 0, 0, + "Stopping program execution..."); + std::cerr << ex.what() << std::endl; + return 1; + } + return 0; +} + +} // namespace + +int run(int argc, char** argv, const Context& ctx) { return runImpl(argc, argv, ctx); } } // namespace bloch::cli diff --git a/src/bloch/cli/cli.hpp b/src/bloch/cli/cli.hpp index 042ffdc..3c402b5 100644 --- a/src/bloch/cli/cli.hpp +++ b/src/bloch/cli/cli.hpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -25,11 +25,11 @@ namespace bloch::cli { - struct Context { - std::string_view version = BLOCH_VERSION; - std::string_view commit = BLOCH_COMMIT_HASH; - }; +struct Context { + std::string_view version = BLOCH_VERSION; + std::string_view commit = BLOCH_COMMIT_HASH; +}; - int run(int argc, char** argv, const Context& ctx = {}); +int run(int argc, char** argv, const Context& ctx = {}); } // namespace bloch::cli diff --git a/src/bloch/compiler/ast/ast.hpp b/src/bloch/compiler/ast/ast.hpp index 6d43383..02c801d 100644 --- a/src/bloch/compiler/ast/ast.hpp +++ b/src/bloch/compiler/ast/ast.hpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,628 +23,625 @@ namespace bloch::compiler { - // The AST is a compact tree built by the parser. Each node carries - // its source position and supports a classic visitor for later stages - // (semantic analysis and execution). - // Only the essentials live here to keep traversal cheap and predictable. - - // Base Node Interfaces - class ASTVisitor; - - struct ASTNode { - int line = 0; - int column = 0; - virtual ~ASTNode() = default; - virtual void accept(ASTVisitor& visitor) = 0; - }; - - struct Statement : public ASTNode {}; - struct Expression : public ASTNode {}; - struct Type : public ASTNode {}; - - // Pre-declared Nodes - struct BlockStatement; - struct AnnotationNode; - struct Parameter; - struct TypeParameter; - - enum class Visibility { Public, Private, Protected }; - - // Variable Declaration - struct VariableDeclaration : public Statement { - std::string name; - std::unique_ptr varType; - std::unique_ptr initializer; - std::vector> annotations; - bool isFinal = false; - bool isTracked = false; - - VariableDeclaration() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Block Statement - // {...} - struct BlockStatement : public Statement { - std::vector> statements; - - BlockStatement() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Expression Statement - struct ExpressionStatement : public Statement { - std::unique_ptr expression; - - ExpressionStatement() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Return Statement - struct ReturnStatement : public Statement { - std::unique_ptr value; - - ReturnStatement() = default; - void accept(ASTVisitor& visitor) override; - }; - - // If Statement - struct IfStatement : public Statement { - std::unique_ptr condition; - std::unique_ptr thenBranch; - std::unique_ptr elseBranch; - - IfStatement() = default; - void accept(ASTVisitor& visitor) override; - }; - - // For Statement - struct ForStatement : public Statement { - std::unique_ptr initializer; - std::unique_ptr condition; - std::unique_ptr increment; - std::unique_ptr body; - - ForStatement() = default; - void accept(ASTVisitor& visitor) override; - }; - - // While Statement - struct WhileStatement : public Statement { - std::unique_ptr condition; - std::unique_ptr body; - - WhileStatement() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Echo Statement - // Print a value at runtime; useful for examples and quick debugging. - struct EchoStatement : public Statement { - std::unique_ptr value; - - EchoStatement() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Reset Statement - struct ResetStatement : public Statement { - std::unique_ptr target; - - ResetStatement() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Measure Statement - // Measure a qubit and push the result into classical memory. - struct MeasureStatement : public Statement { - std::unique_ptr qubit; - - MeasureStatement() = default; - void accept(ASTVisitor& visitor) override; - }; - - // destroy expr; - struct DestroyStatement : public Statement { - std::unique_ptr target; - - DestroyStatement() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Ternary Statement - // cond ? thenBranch : elseBranch - struct TernaryStatement : public Statement { - std::unique_ptr condition; - std::unique_ptr thenBranch; - std::unique_ptr elseBranch; - - TernaryStatement() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Assignment - struct AssignmentStatement : public Statement { - std::string name; - std::unique_ptr value; - - AssignmentStatement() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Binary Expression - struct BinaryExpression : public Expression { - std::string op; - std::unique_ptr left; - std::unique_ptr right; - - BinaryExpression(const std::string& op, std::unique_ptr left, - std::unique_ptr right) - : op(op), left(std::move(left)), right(std::move(right)) {} - void accept(ASTVisitor& visitor) override; - }; - - // Unary Expression - struct UnaryExpression : public Expression { - std::string op; - std::unique_ptr right; - - UnaryExpression(const std::string& op, std::unique_ptr right) - : op(op), right(std::move(right)) {} - void accept(ASTVisitor& visitor) override; - }; - - // Cast Expression - // (type)expr style casts following imperative language conventions. - struct CastExpression : public Expression { - std::unique_ptr targetType; - std::unique_ptr expression; - - CastExpression(std::unique_ptr target, std::unique_ptr expr) - : targetType(std::move(target)), expression(std::move(expr)) {} - void accept(ASTVisitor& visitor) override; - }; - - // Postfix Expression - // Support for i++ and i-- - struct PostfixExpression : public Expression { - std::string op; - std::unique_ptr left; - - PostfixExpression(const std::string& op, std::unique_ptr left) - : op(op), left(std::move(left)) {} - void accept(ASTVisitor& visitor) override; - }; - - // Literal Expression - struct LiteralExpression : public Expression { - std::string value; - std::string literalType; - - LiteralExpression(const std::string& value, const std::string& type) - : value(value), literalType(type) {} - void accept(ASTVisitor& visitor) override; - }; - - struct NullLiteralExpression : public Expression { - NullLiteralExpression() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Variable Expression - struct VariableExpression : public Expression { - std::string name; - - VariableExpression(const std::string& name) : name(name) {} - void accept(ASTVisitor& visitor) override; - }; - - // Call Expression - struct CallExpression : public Expression { - std::unique_ptr callee; - std::vector> arguments; - - CallExpression(std::unique_ptr callee, - std::vector> args) - : callee(std::move(callee)), arguments(std::move(args)) {} - void accept(ASTVisitor& visitor) override; - }; - - // Member access expression: object.member - struct MemberAccessExpression : public Expression { - std::unique_ptr object; - std::string member; - - MemberAccessExpression() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Object creation - struct NewExpression : public Expression { - std::unique_ptr classType; - std::vector> arguments; - - NewExpression() = default; - void accept(ASTVisitor& visitor) override; - }; - - // this - struct ThisExpression : public Expression { - ThisExpression() = default; - void accept(ASTVisitor& visitor) override; - }; - - // super - struct SuperExpression : public Expression { - SuperExpression() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Index Expression a[i] - // Indexing into arrays (bounds/typing checked later). - struct IndexExpression : public Expression { - std::unique_ptr collection; - std::unique_ptr index; - - IndexExpression() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Array Literal Expression - // {a, b, c} literal; type is inferred or validated during semantics/runtime. - struct ArrayLiteralExpression : public Expression { - std::vector> elements; - - ArrayLiteralExpression(std::vector> elems) - : elements(std::move(elems)) {} - void accept(ASTVisitor& visitor) override; - }; - - // Parenthesized Expression - // (expr) keeps source intent; may be useful for diagnostics. - struct ParenthesizedExpression : public Expression { - std::unique_ptr expression; - - ParenthesizedExpression(std::unique_ptr expr) : expression(std::move(expr)) {} - void accept(ASTVisitor& visitor) override; - }; - - // Measure Expression - // Inline measurement returns a bit value. - struct MeasureExpression : public Expression { - std::unique_ptr qubit; - - MeasureExpression(std::unique_ptr qubit) : qubit(std::move(qubit)) {} - void accept(ASTVisitor& visitor) override; - }; - - // Assignment Expression - struct AssignmentExpression : public Expression { - std::string name; - std::unique_ptr value; - - AssignmentExpression(std::string name, std::unique_ptr value) - : name(std::move(name)), value(std::move(value)) {} - void accept(ASTVisitor& visitor) override; - }; - - // object.member = value - struct MemberAssignmentExpression : public Expression { - std::unique_ptr object; - std::string member; - std::unique_ptr value; - - MemberAssignmentExpression(std::unique_ptr object, std::string member, - std::unique_ptr value) - : object(std::move(object)), member(std::move(member)), value(std::move(value)) {} - void accept(ASTVisitor& visitor) override; - }; - - // Array element assignment expression: collection[index] = value - struct ArrayAssignmentExpression : public Expression { - std::unique_ptr collection; - std::unique_ptr index; - std::unique_ptr value; - - ArrayAssignmentExpression(std::unique_ptr collection, - std::unique_ptr index, - std::unique_ptr value) - : collection(std::move(collection)), index(std::move(index)), value(std::move(value)) {} - void accept(ASTVisitor& visitor) override; - }; - - // Type Nodes - struct PrimitiveType : public Type { - std::string name; - - PrimitiveType(const std::string& name) : name(name) {} - void accept(ASTVisitor& visitor) override; - }; - - // User-defined or qualified type - struct NamedType : public Type { - std::vector nameParts; - std::vector> typeArguments; - // True when the source contained an explicit '<...>' list. - // This lets semantics distinguish `Foo` (raw/omitted args) from `Foo<>` (diamond). - bool hasTypeArgumentList = false; - - explicit NamedType(std::vector parts) : nameParts(std::move(parts)) {} - void accept(ASTVisitor& visitor) override; - }; - - // Array type - struct ArrayType : public Type { - std::unique_ptr elementType; - // Optional fixed size for the array. If negative, size is unspecified. - int size = -1; - // Optional raw size expression for cases where the size is derived from a - // compile-time constant (e.g. final int n = 4; int[n] a;). Semantic - // analysis resolves this to 'size'. - std::unique_ptr sizeExpression; - - ArrayType(std::unique_ptr elementType, int size = -1, - std::unique_ptr sizeExpr = nullptr) - : elementType(std::move(elementType)), - size(size), - sizeExpression(std::move(sizeExpr)) {} - void accept(ASTVisitor& visitor) override; - }; - - // void - struct VoidType : public Type { - VoidType() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Parameter - struct Parameter : public ASTNode { - std::string name; - std::unique_ptr type; - - Parameter() = default; - void accept(ASTVisitor& visitor) override; - }; - - struct TypeParameter : public ASTNode { - std::string name; - std::unique_ptr bound; // optional upper bound (extends) - - TypeParameter() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Annotation - struct AnnotationNode : public ASTNode { - std::string name; - std::string value = std::string{""}; - bool isFunctionAnnotation = false; - bool isVariableAnnotation = false; - - AnnotationNode() = default; - AnnotationNode(std::string& name, std::string& value) : name(name), value(value) {} - void accept(ASTVisitor& visitor) override; - }; - - // Package declaration at the top of a file: package foo.bar; - struct PackageDeclaration : public ASTNode { - std::vector nameParts; - - PackageDeclaration() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Import declaration: import foo.bar.Baz; or import foo.bar.*; - struct ImportDeclaration : public ASTNode { - std::vector packageParts; - std::optional symbol; - bool isWildcard = false; - - ImportDeclaration() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Class Members - struct ClassMember : public ASTNode { - Visibility visibility = Visibility::Public; - }; - - // Fields - struct FieldDeclaration : public ClassMember { - std::string name; - std::unique_ptr fieldType; - std::unique_ptr initializer; - std::vector> annotations; - bool isFinal = false; - bool isStatic = false; - bool isTracked = false; - - FieldDeclaration() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Methods - struct MethodDeclaration : public ClassMember { - std::string name; - std::vector> params; - std::unique_ptr returnType; - std::unique_ptr body; - std::vector> annotations; - bool hasQuantumAnnotation = false; - bool isStatic = false; - bool isVirtual = false; - bool isOverride = false; - - MethodDeclaration() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Constructor - struct ConstructorDeclaration : public ClassMember { - std::vector> params; - std::unique_ptr body; - bool isDefault = false; - - ConstructorDeclaration() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Destructor - struct DestructorDeclaration : public ClassMember { - std::unique_ptr body; - bool isDefault = false; - - DestructorDeclaration() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Class Declaration - struct ClassDeclaration : public ASTNode { - std::string name; - std::vector> typeParameters; - std::vector baseName; - std::unique_ptr baseType; - bool isStatic = false; - bool isAbstract = false; - std::vector> members; - - ClassDeclaration() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Function Declaration - struct FunctionDeclaration : public ASTNode { - std::string name; - std::vector> params; - std::unique_ptr returnType; - std::unique_ptr body; - std::vector> annotations; - bool hasQuantumAnnotation = false; - bool hasShotsAnnotation = false; - - FunctionDeclaration() = default; - void accept(ASTVisitor& visitor) override; - }; - - // Program - struct Program : public ASTNode { - std::unique_ptr packageDecl; - std::vector> imports; - std::vector> classes; - std::vector> functions; - std::vector> statements; - std::pair shots; - - Program() = default; - - void accept(ASTVisitor& visitor) override; - }; - - // Visitor Interface - class ASTVisitor { - public: - virtual ~ASTVisitor() = default; - - virtual void visit(VariableDeclaration& node) = 0; - virtual void visit(BlockStatement& node) = 0; - virtual void visit(ExpressionStatement& node) = 0; - virtual void visit(ReturnStatement& node) = 0; - virtual void visit(IfStatement& node) = 0; - virtual void visit(ForStatement& node) = 0; - virtual void visit(WhileStatement& node) = 0; - virtual void visit(EchoStatement& node) = 0; - virtual void visit(ResetStatement& node) = 0; - virtual void visit(MeasureStatement& node) = 0; - virtual void visit(DestroyStatement& node) = 0; - virtual void visit(TernaryStatement& node) = 0; - virtual void visit(AssignmentStatement& node) = 0; - - virtual void visit(BinaryExpression& node) = 0; - virtual void visit(UnaryExpression& node) = 0; - virtual void visit(CastExpression& node) = 0; - virtual void visit(PostfixExpression& node) = 0; - virtual void visit(LiteralExpression& node) = 0; - virtual void visit(NullLiteralExpression& node) = 0; - virtual void visit(VariableExpression& node) = 0; - virtual void visit(CallExpression& node) = 0; - virtual void visit(MemberAccessExpression& node) = 0; - virtual void visit(NewExpression& node) = 0; - virtual void visit(ThisExpression& node) = 0; - virtual void visit(SuperExpression& node) = 0; - virtual void visit(IndexExpression& node) = 0; - virtual void visit(ArrayLiteralExpression& node) = 0; - virtual void visit(ParenthesizedExpression& node) = 0; - virtual void visit(MeasureExpression& node) = 0; - virtual void visit(AssignmentExpression& node) = 0; - virtual void visit(MemberAssignmentExpression& node) = 0; - virtual void visit(ArrayAssignmentExpression& node) = 0; - - virtual void visit(PrimitiveType& node) = 0; - virtual void visit(NamedType& node) = 0; - virtual void visit(ArrayType& node) = 0; - virtual void visit(VoidType& node) = 0; - virtual void visit(TypeParameter& node) = 0; - - virtual void visit(Parameter& node) = 0; - virtual void visit(AnnotationNode& node) = 0; - virtual void visit(PackageDeclaration& node) = 0; - virtual void visit(ImportDeclaration& node) = 0; - virtual void visit(FieldDeclaration& node) = 0; - virtual void visit(MethodDeclaration& node) = 0; - virtual void visit(ConstructorDeclaration& node) = 0; - virtual void visit(DestructorDeclaration& node) = 0; - virtual void visit(ClassDeclaration& node) = 0; - virtual void visit(FunctionDeclaration& node) = 0; - virtual void visit(Program& node) = 0; - }; - - // Inline accept implementations - inline void VariableDeclaration::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void BlockStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void ExpressionStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void ReturnStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void IfStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void ForStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void WhileStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void EchoStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void ResetStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void MeasureStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void DestroyStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void TernaryStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void AssignmentStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void BinaryExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void UnaryExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void CastExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void PostfixExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void LiteralExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void NullLiteralExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void VariableExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void CallExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void MemberAccessExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void NewExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void ThisExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void SuperExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void IndexExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void ArrayLiteralExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void ParenthesizedExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void MeasureExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void AssignmentExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void MemberAssignmentExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void ArrayAssignmentExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void PrimitiveType::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void NamedType::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void ArrayType::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void VoidType::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void Parameter::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void TypeParameter::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void AnnotationNode::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void PackageDeclaration::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void ImportDeclaration::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void FieldDeclaration::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void MethodDeclaration::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void ConstructorDeclaration::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void DestructorDeclaration::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void ClassDeclaration::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void FunctionDeclaration::accept(ASTVisitor& visitor) { visitor.visit(*this); } - inline void Program::accept(ASTVisitor& visitor) { visitor.visit(*this); } +// The AST is a compact tree built by the parser. Each node carries +// its source position and supports a classic visitor for later stages +// (semantic analysis and execution). +// Only the essentials live here to keep traversal cheap and predictable. + +// Base Node Interfaces +class ASTVisitor; + +struct ASTNode { + int line = 0; + int column = 0; + virtual ~ASTNode() = default; + virtual void accept(ASTVisitor& visitor) = 0; +}; + +struct Statement : public ASTNode {}; +struct Expression : public ASTNode {}; +struct Type : public ASTNode {}; + +// Pre-declared Nodes +struct BlockStatement; +struct AnnotationNode; +struct Parameter; +struct TypeParameter; + +enum class Visibility { Public, Private, Protected }; + +// Variable Declaration +struct VariableDeclaration : public Statement { + std::string name; + std::unique_ptr varType; + std::unique_ptr initializer; + std::vector> annotations; + bool isFinal = false; + bool isTracked = false; + + VariableDeclaration() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Block Statement +// {...} +struct BlockStatement : public Statement { + std::vector> statements; + + BlockStatement() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Expression Statement +struct ExpressionStatement : public Statement { + std::unique_ptr expression; + + ExpressionStatement() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Return Statement +struct ReturnStatement : public Statement { + std::unique_ptr value; + + ReturnStatement() = default; + void accept(ASTVisitor& visitor) override; +}; + +// If Statement +struct IfStatement : public Statement { + std::unique_ptr condition; + std::unique_ptr thenBranch; + std::unique_ptr elseBranch; + + IfStatement() = default; + void accept(ASTVisitor& visitor) override; +}; + +// For Statement +struct ForStatement : public Statement { + std::unique_ptr initializer; + std::unique_ptr condition; + std::unique_ptr increment; + std::unique_ptr body; + + ForStatement() = default; + void accept(ASTVisitor& visitor) override; +}; + +// While Statement +struct WhileStatement : public Statement { + std::unique_ptr condition; + std::unique_ptr body; + + WhileStatement() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Echo Statement +// Print a value at runtime; useful for examples and quick debugging. +struct EchoStatement : public Statement { + std::unique_ptr value; + + EchoStatement() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Reset Statement +struct ResetStatement : public Statement { + std::unique_ptr target; + + ResetStatement() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Measure Statement +// Measure a qubit and push the result into classical memory. +struct MeasureStatement : public Statement { + std::unique_ptr qubit; + + MeasureStatement() = default; + void accept(ASTVisitor& visitor) override; +}; + +// destroy expr; +struct DestroyStatement : public Statement { + std::unique_ptr target; + + DestroyStatement() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Ternary Statement +// cond ? thenBranch : elseBranch +struct TernaryStatement : public Statement { + std::unique_ptr condition; + std::unique_ptr thenBranch; + std::unique_ptr elseBranch; + + TernaryStatement() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Assignment +struct AssignmentStatement : public Statement { + std::string name; + std::unique_ptr value; + + AssignmentStatement() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Binary Expression +struct BinaryExpression : public Expression { + std::string op; + std::unique_ptr left; + std::unique_ptr right; + + BinaryExpression(const std::string& op, std::unique_ptr left, + std::unique_ptr right) + : op(op), left(std::move(left)), right(std::move(right)) {} + void accept(ASTVisitor& visitor) override; +}; + +// Unary Expression +struct UnaryExpression : public Expression { + std::string op; + std::unique_ptr right; + + UnaryExpression(const std::string& op, std::unique_ptr right) + : op(op), right(std::move(right)) {} + void accept(ASTVisitor& visitor) override; +}; + +// Cast Expression +// (type)expr style casts following imperative language conventions. +struct CastExpression : public Expression { + std::unique_ptr targetType; + std::unique_ptr expression; + + CastExpression(std::unique_ptr target, std::unique_ptr expr) + : targetType(std::move(target)), expression(std::move(expr)) {} + void accept(ASTVisitor& visitor) override; +}; + +// Postfix Expression +// Support for i++ and i-- +struct PostfixExpression : public Expression { + std::string op; + std::unique_ptr left; + + PostfixExpression(const std::string& op, std::unique_ptr left) + : op(op), left(std::move(left)) {} + void accept(ASTVisitor& visitor) override; +}; + +// Literal Expression +struct LiteralExpression : public Expression { + std::string value; + std::string literalType; + + LiteralExpression(const std::string& value, const std::string& type) + : value(value), literalType(type) {} + void accept(ASTVisitor& visitor) override; +}; + +struct NullLiteralExpression : public Expression { + NullLiteralExpression() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Variable Expression +struct VariableExpression : public Expression { + std::string name; + + VariableExpression(const std::string& name) : name(name) {} + void accept(ASTVisitor& visitor) override; +}; + +// Call Expression +struct CallExpression : public Expression { + std::unique_ptr callee; + std::vector> arguments; + + CallExpression(std::unique_ptr callee, + std::vector> args) + : callee(std::move(callee)), arguments(std::move(args)) {} + void accept(ASTVisitor& visitor) override; +}; + +// Member access expression: object.member +struct MemberAccessExpression : public Expression { + std::unique_ptr object; + std::string member; + + MemberAccessExpression() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Object creation +struct NewExpression : public Expression { + std::unique_ptr classType; + std::vector> arguments; + + NewExpression() = default; + void accept(ASTVisitor& visitor) override; +}; + +// this +struct ThisExpression : public Expression { + ThisExpression() = default; + void accept(ASTVisitor& visitor) override; +}; + +// super +struct SuperExpression : public Expression { + SuperExpression() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Index Expression a[i] +// Indexing into arrays (bounds/typing checked later). +struct IndexExpression : public Expression { + std::unique_ptr collection; + std::unique_ptr index; + + IndexExpression() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Array Literal Expression +// {a, b, c} literal; type is inferred or validated during semantics/runtime. +struct ArrayLiteralExpression : public Expression { + std::vector> elements; + + ArrayLiteralExpression(std::vector> elems) + : elements(std::move(elems)) {} + void accept(ASTVisitor& visitor) override; +}; + +// Parenthesized Expression +// (expr) keeps source intent; may be useful for diagnostics. +struct ParenthesizedExpression : public Expression { + std::unique_ptr expression; + + ParenthesizedExpression(std::unique_ptr expr) : expression(std::move(expr)) {} + void accept(ASTVisitor& visitor) override; +}; + +// Measure Expression +// Inline measurement returns a bit value. +struct MeasureExpression : public Expression { + std::unique_ptr qubit; + + MeasureExpression(std::unique_ptr qubit) : qubit(std::move(qubit)) {} + void accept(ASTVisitor& visitor) override; +}; + +// Assignment Expression +struct AssignmentExpression : public Expression { + std::string name; + std::unique_ptr value; + + AssignmentExpression(std::string name, std::unique_ptr value) + : name(std::move(name)), value(std::move(value)) {} + void accept(ASTVisitor& visitor) override; +}; + +// object.member = value +struct MemberAssignmentExpression : public Expression { + std::unique_ptr object; + std::string member; + std::unique_ptr value; + + MemberAssignmentExpression(std::unique_ptr object, std::string member, + std::unique_ptr value) + : object(std::move(object)), member(std::move(member)), value(std::move(value)) {} + void accept(ASTVisitor& visitor) override; +}; + +// Array element assignment expression: collection[index] = value +struct ArrayAssignmentExpression : public Expression { + std::unique_ptr collection; + std::unique_ptr index; + std::unique_ptr value; + + ArrayAssignmentExpression(std::unique_ptr collection, + std::unique_ptr index, std::unique_ptr value) + : collection(std::move(collection)), index(std::move(index)), value(std::move(value)) {} + void accept(ASTVisitor& visitor) override; +}; + +// Type Nodes +struct PrimitiveType : public Type { + std::string name; + + PrimitiveType(const std::string& name) : name(name) {} + void accept(ASTVisitor& visitor) override; +}; + +// User-defined or qualified type +struct NamedType : public Type { + std::vector nameParts; + std::vector> typeArguments; + // True when the source contained an explicit '<...>' list. + // This lets semantics distinguish `Foo` (raw/omitted args) from `Foo<>` (diamond). + bool hasTypeArgumentList = false; + + explicit NamedType(std::vector parts) : nameParts(std::move(parts)) {} + void accept(ASTVisitor& visitor) override; +}; + +// Array type +struct ArrayType : public Type { + std::unique_ptr elementType; + // Optional fixed size for the array. If negative, size is unspecified. + int size = -1; + // Optional raw size expression for cases where the size is derived from a + // compile-time constant (e.g. final int n = 4; int[n] a;). Semantic + // analysis resolves this to 'size'. + std::unique_ptr sizeExpression; + + ArrayType(std::unique_ptr elementType, int size = -1, + std::unique_ptr sizeExpr = nullptr) + : elementType(std::move(elementType)), size(size), sizeExpression(std::move(sizeExpr)) {} + void accept(ASTVisitor& visitor) override; +}; + +// void +struct VoidType : public Type { + VoidType() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Parameter +struct Parameter : public ASTNode { + std::string name; + std::unique_ptr type; + + Parameter() = default; + void accept(ASTVisitor& visitor) override; +}; + +struct TypeParameter : public ASTNode { + std::string name; + std::unique_ptr bound; // optional upper bound (extends) + + TypeParameter() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Annotation +struct AnnotationNode : public ASTNode { + std::string name; + std::string value = std::string{""}; + bool isFunctionAnnotation = false; + bool isVariableAnnotation = false; + + AnnotationNode() = default; + AnnotationNode(std::string& name, std::string& value) : name(name), value(value) {} + void accept(ASTVisitor& visitor) override; +}; + +// Package declaration at the top of a file: package foo.bar; +struct PackageDeclaration : public ASTNode { + std::vector nameParts; + + PackageDeclaration() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Import declaration: import foo.bar.Baz; or import foo.bar.*; +struct ImportDeclaration : public ASTNode { + std::vector packageParts; + std::optional symbol; + bool isWildcard = false; + + ImportDeclaration() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Class Members +struct ClassMember : public ASTNode { + Visibility visibility = Visibility::Public; +}; + +// Fields +struct FieldDeclaration : public ClassMember { + std::string name; + std::unique_ptr fieldType; + std::unique_ptr initializer; + std::vector> annotations; + bool isFinal = false; + bool isStatic = false; + bool isTracked = false; + + FieldDeclaration() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Methods +struct MethodDeclaration : public ClassMember { + std::string name; + std::vector> params; + std::unique_ptr returnType; + std::unique_ptr body; + std::vector> annotations; + bool hasQuantumAnnotation = false; + bool isStatic = false; + bool isVirtual = false; + bool isOverride = false; + + MethodDeclaration() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Constructor +struct ConstructorDeclaration : public ClassMember { + std::vector> params; + std::unique_ptr body; + bool isDefault = false; + + ConstructorDeclaration() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Destructor +struct DestructorDeclaration : public ClassMember { + std::unique_ptr body; + bool isDefault = false; + + DestructorDeclaration() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Class Declaration +struct ClassDeclaration : public ASTNode { + std::string name; + std::vector> typeParameters; + std::vector baseName; + std::unique_ptr baseType; + bool isStatic = false; + bool isAbstract = false; + std::vector> members; + + ClassDeclaration() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Function Declaration +struct FunctionDeclaration : public ASTNode { + std::string name; + std::vector> params; + std::unique_ptr returnType; + std::unique_ptr body; + std::vector> annotations; + bool hasQuantumAnnotation = false; + bool hasShotsAnnotation = false; + + FunctionDeclaration() = default; + void accept(ASTVisitor& visitor) override; +}; + +// Program +struct Program : public ASTNode { + std::unique_ptr packageDecl; + std::vector> imports; + std::vector> classes; + std::vector> functions; + std::vector> statements; + std::pair shots; + + Program() = default; + + void accept(ASTVisitor& visitor) override; +}; + +// Visitor Interface +class ASTVisitor { + public: + virtual ~ASTVisitor() = default; + + virtual void visit(VariableDeclaration& node) = 0; + virtual void visit(BlockStatement& node) = 0; + virtual void visit(ExpressionStatement& node) = 0; + virtual void visit(ReturnStatement& node) = 0; + virtual void visit(IfStatement& node) = 0; + virtual void visit(ForStatement& node) = 0; + virtual void visit(WhileStatement& node) = 0; + virtual void visit(EchoStatement& node) = 0; + virtual void visit(ResetStatement& node) = 0; + virtual void visit(MeasureStatement& node) = 0; + virtual void visit(DestroyStatement& node) = 0; + virtual void visit(TernaryStatement& node) = 0; + virtual void visit(AssignmentStatement& node) = 0; + + virtual void visit(BinaryExpression& node) = 0; + virtual void visit(UnaryExpression& node) = 0; + virtual void visit(CastExpression& node) = 0; + virtual void visit(PostfixExpression& node) = 0; + virtual void visit(LiteralExpression& node) = 0; + virtual void visit(NullLiteralExpression& node) = 0; + virtual void visit(VariableExpression& node) = 0; + virtual void visit(CallExpression& node) = 0; + virtual void visit(MemberAccessExpression& node) = 0; + virtual void visit(NewExpression& node) = 0; + virtual void visit(ThisExpression& node) = 0; + virtual void visit(SuperExpression& node) = 0; + virtual void visit(IndexExpression& node) = 0; + virtual void visit(ArrayLiteralExpression& node) = 0; + virtual void visit(ParenthesizedExpression& node) = 0; + virtual void visit(MeasureExpression& node) = 0; + virtual void visit(AssignmentExpression& node) = 0; + virtual void visit(MemberAssignmentExpression& node) = 0; + virtual void visit(ArrayAssignmentExpression& node) = 0; + + virtual void visit(PrimitiveType& node) = 0; + virtual void visit(NamedType& node) = 0; + virtual void visit(ArrayType& node) = 0; + virtual void visit(VoidType& node) = 0; + virtual void visit(TypeParameter& node) = 0; + + virtual void visit(Parameter& node) = 0; + virtual void visit(AnnotationNode& node) = 0; + virtual void visit(PackageDeclaration& node) = 0; + virtual void visit(ImportDeclaration& node) = 0; + virtual void visit(FieldDeclaration& node) = 0; + virtual void visit(MethodDeclaration& node) = 0; + virtual void visit(ConstructorDeclaration& node) = 0; + virtual void visit(DestructorDeclaration& node) = 0; + virtual void visit(ClassDeclaration& node) = 0; + virtual void visit(FunctionDeclaration& node) = 0; + virtual void visit(Program& node) = 0; +}; + +// Inline accept implementations +inline void VariableDeclaration::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void BlockStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void ExpressionStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void ReturnStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void IfStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void ForStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void WhileStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void EchoStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void ResetStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void MeasureStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void DestroyStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void TernaryStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void AssignmentStatement::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void BinaryExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void UnaryExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void CastExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void PostfixExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void LiteralExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void NullLiteralExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void VariableExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void CallExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void MemberAccessExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void NewExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void ThisExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void SuperExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void IndexExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void ArrayLiteralExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void ParenthesizedExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void MeasureExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void AssignmentExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void MemberAssignmentExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void ArrayAssignmentExpression::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void PrimitiveType::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void NamedType::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void ArrayType::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void VoidType::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void Parameter::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void TypeParameter::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void AnnotationNode::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void PackageDeclaration::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void ImportDeclaration::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void FieldDeclaration::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void MethodDeclaration::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void ConstructorDeclaration::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void DestructorDeclaration::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void ClassDeclaration::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void FunctionDeclaration::accept(ASTVisitor& visitor) { visitor.visit(*this); } +inline void Program::accept(ASTVisitor& visitor) { visitor.visit(*this); } } // namespace bloch::compiler diff --git a/src/bloch/compiler/import/module_loader.cpp b/src/bloch/compiler/import/module_loader.cpp index d2b3558..70b1434 100644 --- a/src/bloch/compiler/import/module_loader.cpp +++ b/src/bloch/compiler/import/module_loader.cpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -26,222 +26,210 @@ namespace bloch::compiler { - using support::BlochError; - using support::ErrorCategory; - namespace fs = std::filesystem; +using support::BlochError; +using support::ErrorCategory; +namespace fs = std::filesystem; - ModuleLoader::ModuleLoader(std::vector searchPaths) - : m_searchPaths(std::move(searchPaths)) {} +ModuleLoader::ModuleLoader(std::vector searchPaths) + : m_searchPaths(std::move(searchPaths)) {} - std::string ModuleLoader::joinQualified(const std::vector& parts) { - std::ostringstream oss; - for (size_t i = 0; i < parts.size(); ++i) { - if (i) - oss << "."; - oss << parts[i]; - } - return oss.str(); +std::string ModuleLoader::joinQualified(const std::vector& parts) { + std::ostringstream oss; + for (size_t i = 0; i < parts.size(); ++i) { + if (i) + oss << "."; + oss << parts[i]; } - - namespace { - std::string joinQualifiedLocal(const std::vector& parts) { - std::ostringstream oss; - for (size_t i = 0; i < parts.size(); ++i) { - if (i) - oss << "."; - oss << parts[i]; - } + return oss.str(); +} + +namespace { +std::string joinQualifiedLocal(const std::vector& parts) { + std::ostringstream oss; + for (size_t i = 0; i < parts.size(); ++i) { + if (i) + oss << "."; + oss << parts[i]; + } + return oss.str(); +} + +std::string formatPackageName(const std::vector& parts) { + if (parts.empty()) + return "default package"; + return joinQualifiedLocal(parts); +} + +std::string formatImportName(const ImportDeclaration& imp) { + std::ostringstream oss; + if (!imp.packageParts.empty()) { + oss << joinQualifiedLocal(imp.packageParts); + if (imp.isWildcard) { + oss << ".*"; return oss.str(); } - - std::string formatPackageName(const std::vector& parts) { - if (parts.empty()) - return "default package"; - return joinQualifiedLocal(parts); + if (imp.symbol) { + oss << "." << *imp.symbol; + return oss.str(); } + return oss.str(); + } + if (imp.isWildcard) + return "*"; + if (imp.symbol) + return *imp.symbol; + return ""; +} +} // namespace + +std::string ModuleLoader::canonicalize(const std::string& path) const { + std::error_code ec; + fs::path p(path); + fs::path abs = fs::absolute(p, ec); + if (!ec) { + fs::path canon = fs::weakly_canonical(abs, ec); + if (!ec) + return canon.string(); + } + return p.lexically_normal().string(); +} - std::string formatImportName(const ImportDeclaration& imp) { - std::ostringstream oss; - if (!imp.packageParts.empty()) { - oss << joinQualifiedLocal(imp.packageParts); - if (imp.isWildcard) { - oss << ".*"; - return oss.str(); - } - if (imp.symbol) { - oss << "." << *imp.symbol; - return oss.str(); - } - return oss.str(); - } - if (imp.isWildcard) - return "*"; - if (imp.symbol) - return *imp.symbol; - return ""; - } - } // namespace +std::unique_ptr ModuleLoader::parseFile(const std::string& path) const { + std::ifstream in(path); + if (!in) { + throw BlochError(ErrorCategory::Parse, 0, 0, "failed to open '" + path + "'"); + } + std::string src((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + Lexer lexer(src); + std::vector tokens = lexer.tokenize(); + Parser parser(std::move(tokens)); + return parser.parse(); +} + +std::string ModuleLoader::resolveImportPath(const std::vector& parts, + const std::string& fromDir) const { + fs::path relative; + for (const auto& p : parts) + relative /= p; + relative += ".bloch"; + + bool preferSearchPaths = !parts.empty() && parts.front() == "bloch"; + + // Search order: + // - default: importing file dir, configured search paths, current working dir. + // - bloch.* imports: configured search paths first to avoid project shadowing stdlib. + std::vector bases; + if (preferSearchPaths) { + for (const auto& p : m_searchPaths) + bases.emplace_back(p); + bases.emplace_back(fromDir); + bases.push_back(fs::current_path()); + } else { + bases.emplace_back(fromDir); + for (const auto& p : m_searchPaths) + bases.emplace_back(p); + bases.push_back(fs::current_path()); + } - std::string ModuleLoader::canonicalize(const std::string& path) const { + for (const auto& base : bases) { std::error_code ec; - fs::path p(path); - fs::path abs = fs::absolute(p, ec); - if (!ec) { - fs::path canon = fs::weakly_canonical(abs, ec); - if (!ec) - return canon.string(); - } - return p.lexically_normal().string(); + fs::path candidate = fs::weakly_canonical(base / relative, ec); + if (ec) + continue; + if (fs::exists(candidate, ec) && fs::is_regular_file(candidate, ec)) + return candidate.string(); } - - std::unique_ptr ModuleLoader::parseFile(const std::string& path) const { - std::ifstream in(path); - if (!in) { - throw BlochError(ErrorCategory::Parse, 0, 0, "failed to open '" + path + "'"); - } - std::string src((std::istreambuf_iterator(in)), std::istreambuf_iterator()); - Lexer lexer(src); - std::vector tokens = lexer.tokenize(); - Parser parser(std::move(tokens)); - return parser.parse(); + return ""; +} + +std::vector ModuleLoader::resolvePackageModules( + const std::vector& packageParts, const std::string& fromDir) const { + fs::path relative; + for (const auto& p : packageParts) + relative /= p; + + bool preferSearchPaths = !packageParts.empty() && packageParts.front() == "bloch"; + + std::vector bases; + if (preferSearchPaths) { + for (const auto& p : m_searchPaths) + bases.emplace_back(p); + bases.emplace_back(fromDir); + bases.push_back(fs::current_path()); + } else { + bases.emplace_back(fromDir); + for (const auto& p : m_searchPaths) + bases.emplace_back(p); + bases.push_back(fs::current_path()); } - std::string ModuleLoader::resolveImportPath(const std::vector& parts, - const std::string& fromDir) const { - fs::path relative; - for (const auto& p : parts) relative /= p; - relative += ".bloch"; - - bool preferSearchPaths = !parts.empty() && parts.front() == "bloch"; - - // Search order: - // - default: importing file dir, configured search paths, current working dir. - // - bloch.* imports: configured search paths first to avoid project shadowing stdlib. - std::vector bases; - if (preferSearchPaths) { - for (const auto& p : m_searchPaths) bases.emplace_back(p); - bases.emplace_back(fromDir); - bases.push_back(fs::current_path()); - } else { - bases.emplace_back(fromDir); - for (const auto& p : m_searchPaths) bases.emplace_back(p); - bases.push_back(fs::current_path()); - } - - for (const auto& base : bases) { - std::error_code ec; - fs::path candidate = fs::weakly_canonical(base / relative, ec); + for (const auto& base : bases) { + std::error_code ec; + fs::path candidate = fs::weakly_canonical(base / relative, ec); + if (ec) + continue; + if (!fs::exists(candidate, ec) || !fs::is_directory(candidate, ec)) + continue; + + std::vector modules; + for (const auto& entry : fs::directory_iterator(candidate, ec)) { if (ec) + break; + if (!entry.is_regular_file(ec)) continue; - if (fs::exists(candidate, ec) && fs::is_regular_file(candidate, ec)) - return candidate.string(); + fs::path p = entry.path(); + if (p.extension() == ".bloch") + modules.push_back(p.string()); } - return ""; - } - - std::vector ModuleLoader::resolvePackageModules( - const std::vector& packageParts, const std::string& fromDir) const { - fs::path relative; - for (const auto& p : packageParts) relative /= p; - - bool preferSearchPaths = !packageParts.empty() && packageParts.front() == "bloch"; - - std::vector bases; - if (preferSearchPaths) { - for (const auto& p : m_searchPaths) bases.emplace_back(p); - bases.emplace_back(fromDir); - bases.push_back(fs::current_path()); - } else { - bases.emplace_back(fromDir); - for (const auto& p : m_searchPaths) bases.emplace_back(p); - bases.push_back(fs::current_path()); + if (!modules.empty()) { + std::sort(modules.begin(), modules.end()); + return modules; } + } - for (const auto& base : bases) { - std::error_code ec; - fs::path candidate = fs::weakly_canonical(base / relative, ec); - if (ec) - continue; - if (!fs::exists(candidate, ec) || !fs::is_directory(candidate, ec)) - continue; - - std::vector modules; - for (const auto& entry : fs::directory_iterator(candidate, ec)) { - if (ec) - break; - if (!entry.is_regular_file(ec)) - continue; - fs::path p = entry.path(); - if (p.extension() == ".bloch") - modules.push_back(p.string()); - } - if (!modules.empty()) { - std::sort(modules.begin(), modules.end()); - return modules; - } - } + return {}; +} +std::vector ModuleLoader::packagePartsFor(const std::string& canonicalPath) const { + auto it = m_cache.find(canonicalPath); + if (it == m_cache.end() || !it->second || !it->second->packageDecl) return {}; - } + return it->second->packageDecl->nameParts; +} - std::vector ModuleLoader::packagePartsFor(const std::string& canonicalPath) const { - auto it = m_cache.find(canonicalPath); - if (it == m_cache.end() || !it->second || !it->second->packageDecl) - return {}; - return it->second->packageDecl->nameParts; +void ModuleLoader::loadModule(const std::string& path) { + std::string canon = canonicalize(path); + auto cyc = std::find(m_stack.begin(), m_stack.end(), canon); + if (cyc != m_stack.end()) { + std::ostringstream oss; + oss << "import cycle detected: "; + for (auto it = cyc; it != m_stack.end(); ++it) + oss << *it << " -> "; + oss << canon; + throw BlochError(ErrorCategory::Semantic, 0, 0, oss.str()); } - - void ModuleLoader::loadModule(const std::string& path) { - std::string canon = canonicalize(path); - auto cyc = std::find(m_stack.begin(), m_stack.end(), canon); - if (cyc != m_stack.end()) { - std::ostringstream oss; - oss << "import cycle detected: "; - for (auto it = cyc; it != m_stack.end(); ++it) oss << *it << " -> "; - oss << canon; - throw BlochError(ErrorCategory::Semantic, 0, 0, oss.str()); - } - if (m_cache.count(canon)) - return; - - m_stack.push_back(canon); - std::unique_ptr program = parseFile(canon); - - fs::path parent = fs::path(canon).parent_path(); - for (auto& imp : program->imports) { - if (!imp) - continue; - if (imp->isWildcard) { - std::vector targets = - resolvePackageModules(imp->packageParts, parent.string()); - if (targets.empty()) { - throw BlochError(ErrorCategory::Semantic, imp->line, imp->column, - "import '" + formatImportName(*imp) + "' not found"); - } - for (const auto& target : targets) { - std::string canonTarget = canonicalize(target); - if (canonTarget == canon) - continue; - loadModule(target); - std::vector actualPackage = packagePartsFor(canonTarget); - if (actualPackage != imp->packageParts) { - throw BlochError(ErrorCategory::Semantic, imp->line, imp->column, - "import '" + formatImportName(*imp) + - "' resolved to package '" + - formatPackageName(actualPackage) + "', expected '" + - formatPackageName(imp->packageParts) + "'"); - } - } - } else if (imp->symbol) { - std::vector parts = imp->packageParts; - parts.push_back(*imp->symbol); - std::string target = resolveImportPath(parts, parent.string()); - if (target.empty()) { - throw BlochError(ErrorCategory::Semantic, imp->line, imp->column, - "import '" + formatImportName(*imp) + "' not found"); - } - loadModule(target); + if (m_cache.count(canon)) + return; + + m_stack.push_back(canon); + std::unique_ptr program = parseFile(canon); + + fs::path parent = fs::path(canon).parent_path(); + for (auto& imp : program->imports) { + if (!imp) + continue; + if (imp->isWildcard) { + std::vector targets = + resolvePackageModules(imp->packageParts, parent.string()); + if (targets.empty()) { + throw BlochError(ErrorCategory::Semantic, imp->line, imp->column, + "import '" + formatImportName(*imp) + "' not found"); + } + for (const auto& target : targets) { std::string canonTarget = canonicalize(target); + if (canonTarget == canon) + continue; + loadModule(target); std::vector actualPackage = packagePartsFor(canonTarget); if (actualPackage != imp->packageParts) { throw BlochError(ErrorCategory::Semantic, imp->line, imp->column, @@ -250,71 +238,91 @@ namespace bloch::compiler { formatPackageName(actualPackage) + "', expected '" + formatPackageName(imp->packageParts) + "'"); } - } else { - throw BlochError( - ErrorCategory::Semantic, imp->line, imp->column, - "import '" + formatImportName(*imp) + "' is missing a symbol or wildcard"); } + } else if (imp->symbol) { + std::vector parts = imp->packageParts; + parts.push_back(*imp->symbol); + std::string target = resolveImportPath(parts, parent.string()); + if (target.empty()) { + throw BlochError(ErrorCategory::Semantic, imp->line, imp->column, + "import '" + formatImportName(*imp) + "' not found"); + } + loadModule(target); + std::string canonTarget = canonicalize(target); + std::vector actualPackage = packagePartsFor(canonTarget); + if (actualPackage != imp->packageParts) { + throw BlochError(ErrorCategory::Semantic, imp->line, imp->column, + "import '" + formatImportName(*imp) + "' resolved to package '" + + formatPackageName(actualPackage) + "', expected '" + + formatPackageName(imp->packageParts) + "'"); + } + } else { + throw BlochError( + ErrorCategory::Semantic, imp->line, imp->column, + "import '" + formatImportName(*imp) + "' is missing a symbol or wildcard"); } - - program->imports.clear(); - m_cache[canon] = std::move(program); - m_loadOrder.push_back(canon); - m_stack.pop_back(); } - std::unique_ptr ModuleLoader::load(const std::string& entryFile) { - m_cache.clear(); - m_loadOrder.clear(); - m_stack.clear(); - - // Load implicit root Object first when available. This keeps class inheritance - // rooted even when user code omits an explicit import. - std::string entryCanonical = canonicalize(entryFile); - fs::path entryParent = fs::path(entryCanonical).parent_path(); - std::string stdlibObject = - resolveImportPath({"bloch", "lang", "Object"}, entryParent.string()); - if (!stdlibObject.empty()) { - loadModule(stdlibObject); - } - - loadModule(entryFile); + program->imports.clear(); + m_cache[canon] = std::move(program); + m_loadOrder.push_back(canon); + m_stack.pop_back(); +} + +std::unique_ptr ModuleLoader::load(const std::string& entryFile) { + m_cache.clear(); + m_loadOrder.clear(); + m_stack.clear(); + + // Load implicit root Object first when available. This keeps class inheritance + // rooted even when user code omits an explicit import. + std::string entryCanonical = canonicalize(entryFile); + fs::path entryParent = fs::path(entryCanonical).parent_path(); + std::string stdlibObject = resolveImportPath({"bloch", "lang", "Object"}, entryParent.string()); + if (!stdlibObject.empty()) { + loadModule(stdlibObject); + } - std::unique_ptr merged = std::make_unique(); - for (const auto& path : m_loadOrder) { - std::unique_ptr& mod = m_cache[path]; - for (auto& cls : mod->classes) merged->classes.push_back(std::move(cls)); - for (auto& fn : mod->functions) merged->functions.push_back(std::move(fn)); - for (auto& stmt : mod->statements) merged->statements.push_back(std::move(stmt)); - } + loadModule(entryFile); + + std::unique_ptr merged = std::make_unique(); + for (const auto& path : m_loadOrder) { + std::unique_ptr& mod = m_cache[path]; + for (auto& cls : mod->classes) + merged->classes.push_back(std::move(cls)); + for (auto& fn : mod->functions) + merged->functions.push_back(std::move(fn)); + for (auto& stmt : mod->statements) + merged->statements.push_back(std::move(stmt)); + } - size_t mainCount = 0; - for (std::unique_ptr& fn : merged->functions) { - if (fn && fn->name == "main") { - ++mainCount; - if (fn->hasShotsAnnotation) { - for (std::unique_ptr& annotation : fn->annotations) { - if (annotation && annotation->name == "shots") { - int shotCount = std::stoi(annotation->value); - merged->shots = {true, shotCount}; - } + size_t mainCount = 0; + for (std::unique_ptr& fn : merged->functions) { + if (fn && fn->name == "main") { + ++mainCount; + if (fn->hasShotsAnnotation) { + for (std::unique_ptr& annotation : fn->annotations) { + if (annotation && annotation->name == "shots") { + int shotCount = std::stoi(annotation->value); + merged->shots = {true, shotCount}; } - } else { - merged->shots = {false, 1}; } + } else { + merged->shots = {false, 1}; } } + } - if (mainCount == 0) { - throw BlochError(ErrorCategory::Semantic, 0, 0, - "No 'main' function found across imported modules"); - } - if (mainCount > 1) { - throw BlochError(ErrorCategory::Semantic, 0, 0, - "Multiple 'main' functions found across imported modules"); - } - - return merged; + if (mainCount == 0) { + throw BlochError(ErrorCategory::Semantic, 0, 0, + "No 'main' function found across imported modules"); } + if (mainCount > 1) { + throw BlochError(ErrorCategory::Semantic, 0, 0, + "Multiple 'main' functions found across imported modules"); + } + + return merged; +} } // namespace bloch::compiler diff --git a/src/bloch/compiler/import/module_loader.hpp b/src/bloch/compiler/import/module_loader.hpp index 5052f5a..ed211e5 100644 --- a/src/bloch/compiler/import/module_loader.hpp +++ b/src/bloch/compiler/import/module_loader.hpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,33 +23,33 @@ namespace bloch::compiler { - // Resolves and loads imports starting from an entry file, producing a single - // aggregated Program ready for semantic analysis and execution. Imports are - // resolved relative to the importing file and optional search paths. - class ModuleLoader { - public: - explicit ModuleLoader(std::vector searchPaths = {}); - - // Load the entry file and all of its transitive imports, merging them - // into a single Program. Throws BlochError on missing modules, cycles, - // or parse errors. Exactly one main() must exist across the graph. - std::unique_ptr load(const std::string& entryFile); - - private: - std::vector m_searchPaths; - std::unordered_map> m_cache; - std::vector m_loadOrder; - std::vector m_stack; - - std::unique_ptr parseFile(const std::string& path) const; - void loadModule(const std::string& path); - std::string resolveImportPath(const std::vector& parts, - const std::string& fromDir) const; - std::vector resolvePackageModules(const std::vector& packageParts, - const std::string& fromDir) const; - std::vector packagePartsFor(const std::string& canonicalPath) const; - std::string canonicalize(const std::string& path) const; - static std::string joinQualified(const std::vector& parts); - }; +// Resolves and loads imports starting from an entry file, producing a single +// aggregated Program ready for semantic analysis and execution. Imports are +// resolved relative to the importing file and optional search paths. +class ModuleLoader { + public: + explicit ModuleLoader(std::vector searchPaths = {}); + + // Load the entry file and all of its transitive imports, merging them + // into a single Program. Throws BlochError on missing modules, cycles, + // or parse errors. Exactly one main() must exist across the graph. + std::unique_ptr load(const std::string& entryFile); + + private: + std::vector m_searchPaths; + std::unordered_map> m_cache; + std::vector m_loadOrder; + std::vector m_stack; + + std::unique_ptr parseFile(const std::string& path) const; + void loadModule(const std::string& path); + std::string resolveImportPath(const std::vector& parts, + const std::string& fromDir) const; + std::vector resolvePackageModules(const std::vector& packageParts, + const std::string& fromDir) const; + std::vector packagePartsFor(const std::string& canonicalPath) const; + std::string canonicalize(const std::string& path) const; + static std::string joinQualified(const std::vector& parts); +}; } // namespace bloch::compiler diff --git a/src/bloch/compiler/lexer/lexer.cpp b/src/bloch/compiler/lexer/lexer.cpp index 1f611fc..510f2d4 100644 --- a/src/bloch/compiler/lexer/lexer.cpp +++ b/src/bloch/compiler/lexer/lexer.cpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,329 +14,348 @@ #include "bloch/compiler/lexer/lexer.hpp" -#include -#include -#include -#include +#include +#include +#include #include -#include +#include + +#include "bloch/support/error/bloch_error.hpp" namespace bloch::compiler { +namespace { + +using Keyword = std::pair; + +constexpr auto kKeywords = std::to_array({ + // Primitive types + {"null", TokenType::Null}, + {"int", TokenType::Int}, + {"long", TokenType::Long}, + {"float", TokenType::Float}, + {"string", TokenType::String}, + {"char", TokenType::Char}, + {"qubit", TokenType::Qubit}, + {"bit", TokenType::Bit}, + {"boolean", TokenType::Boolean}, + + // Boolean literals + {"true", TokenType::True}, + {"false", TokenType::False}, + + // Keywords + {"void", TokenType::Void}, + {"function", TokenType::Function}, + {"return", TokenType::Return}, + {"if", TokenType::If}, + {"else", TokenType::Else}, + {"for", TokenType::For}, + {"while", TokenType::While}, + {"measure", TokenType::Measure}, + {"final", TokenType::Final}, + {"reset", TokenType::Reset}, + {"default", TokenType::Default}, + + // Annotation values + {"quantum", TokenType::Quantum}, + {"tracked", TokenType::Tracked}, + {"shots", TokenType::Shots}, + + // Class system + {"class", TokenType::Class}, + {"public", TokenType::Public}, + {"private", TokenType::Private}, + {"protected", TokenType::Protected}, + {"static", TokenType::Static}, + {"extends", TokenType::Extends}, + {"abstract", TokenType::Abstract}, + {"virtual", TokenType::Virtual}, + {"override", TokenType::Override}, + {"super", TokenType::Super}, + {"this", TokenType::This}, + {"import", TokenType::Import}, + {"package", TokenType::Package}, + {"new", TokenType::New}, + {"constructor", TokenType::Constructor}, + {"destructor", TokenType::Destructor}, + {"destroy", TokenType::Destroy}, + + // Built-ins + {"echo", TokenType::Echo}, +}); + +[[nodiscard]] constexpr bool is_digit(char character) noexcept { + return character >= '0' && character <= '9'; +} + +[[nodiscard]] constexpr bool is_alpha(char character) noexcept { + return (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') || + character == '_'; +} + +[[nodiscard]] constexpr bool is_alphanumeric(char character) noexcept { + return is_alpha(character) || is_digit(character); +} + +[[nodiscard]] constexpr bool is_whitespace(char character) noexcept { + switch (character) { + case ' ': + case '\t': + case '\n': + case '\r': + case '\f': + case '\v': + return true; + default: + return false; + } +} - using support::BlochError; - using support::ErrorCategory; - Lexer::Lexer(const std::string_view source) noexcept - : m_source(source), m_position(0), m_line(1), m_column(1) {} - - std::vector Lexer::tokenize() { - std::vector tokens; - // We repeatedly skip trivia and scan the next meaningful token - // until we run out of input. Always append an explicit EOF token. - while (m_position < m_source.size()) { - skipWhitespace(); - if (m_position < m_source.size()) { - tokens.push_back(scanToken()); - } +[[nodiscard]] constexpr std::optional keyword_type(std::string_view text) noexcept { + for (const auto& [keyword, type] : kKeywords) { + if (text == keyword) { + return type; } - tokens.push_back(makeToken(TokenType::Eof, "")); - return tokens; } + return std::nullopt; +} + +} // namespace + +using support::BlochError; +using support::ErrorCategory; - char Lexer::peek() const noexcept { - return m_position < m_source.size() ? m_source[m_position] : '\0'; +Lexer::Lexer(std::string_view source) noexcept : source_(source) {} + +std::vector Lexer::tokenize() { + std::vector tokens; + + while (!is_at_end()) { + skip_whitespace(); + if (is_at_end()) { + break; + } + + token_start_ = position_; + token_line_ = line_; + token_column_ = column_; + tokens.push_back(scan_token()); } - char Lexer::peekNext() const noexcept { - return (m_position + 1) < m_source.size() ? m_source[m_position + 1] : '\0'; + tokens.push_back(Token{TokenType::Eof, "", line_, column_}); + return tokens; +} + +bool Lexer::is_at_end() const noexcept { return position_ >= source_.size(); } + +char Lexer::peek() const noexcept { return is_at_end() ? '\0' : source_[position_]; } + +char Lexer::peek_next() const noexcept { + return source_.size() - position_ > 1 ? source_[position_ + 1] : '\0'; +} + +char Lexer::advance() noexcept { + const char character = source_[position_++]; + if (character == '\n') { + ++line_; + column_ = 1; + } else { + ++column_; } + return character; +} - char Lexer::advance() noexcept { - char c = m_source[m_position++]; - m_column++; - return c; +bool Lexer::match(char expected) noexcept { + if (is_at_end() || source_[position_] != expected) { + return false; } - bool Lexer::match(char expected) noexcept { - if (m_position >= m_source.size() || m_source[m_position] != expected) { - return false; + advance(); + return true; +} + +void Lexer::skip_whitespace() noexcept { + while (!is_at_end()) { + if (is_whitespace(peek())) { + advance(); + continue; } - m_position++; - m_column++; - return true; - } - void Lexer::skipWhitespace() { - // Eat spaces, tabs and newlines. Treat // as a line comment. - while (m_position < m_source.size()) { - char c = peek(); - if (std::isspace(static_cast(c))) { - if (c == '\n') { - (void)advance(); - m_line++; - m_column = 1; - continue; - } - (void)advance(); - } else if (c == '/' && peekNext() == '/') { - (void)advance(); - (void)advance(); - skipComment(); - } else { - break; - } + if (peek() == '/' && peek_next() == '/') { + advance(); + advance(); + skip_comment(); + continue; } + + break; } +} - void Lexer::skipComment() { - // Consume the rest of the current line. - while (m_position < m_source.size() && m_source[m_position] != '\n') { - (void)advance(); - } +void Lexer::skip_comment() noexcept { + while (!is_at_end() && peek() != '\n') { + advance(); } +} + +void Lexer::report_error(std::string_view message) const { + throw BlochError(ErrorCategory::Lexical, line_, column_, std::string(message)); +} - void Lexer::reportError(const std::string& msg) { - throw BlochError(ErrorCategory::Lexical, m_line, m_column, msg); +Token Lexer::make_token(TokenType type) const { + const auto lexeme = source_.substr(token_start_, position_ - token_start_); + return Token{type, std::string(lexeme), token_line_, token_column_}; +} + +Token Lexer::scan_token() { + const char character = advance(); + + if (is_digit(character)) { + return scan_number(); + } + if (is_alpha(character)) { + return scan_identifier_or_keyword(); } - Token Lexer::makeToken(TokenType type, const std::string& value) { - // Column is adjusted so error spans point to token start. - return Token{type, value, m_line, m_column - static_cast(value.length())}; + switch (character) { + case '=': + return make_token(match('=') ? TokenType::EqualEqual : TokenType::Equals); + case '!': + return make_token(match('=') ? TokenType::BangEqual : TokenType::Bang); + case '+': + return make_token(match('+') ? TokenType::PlusPlus : TokenType::Plus); + case '&': + return make_token(match('&') ? TokenType::AmpersandAmpersand : TokenType::Ampersand); + case '|': + return make_token(match('|') ? TokenType::PipePipe : TokenType::Pipe); + case '^': + return make_token(TokenType::Caret); + case '~': + return make_token(TokenType::Tilde); + case '-': + if (match('>')) { + return make_token(TokenType::Arrow); + } + return make_token(match('-') ? TokenType::MinusMinus : TokenType::Minus); + case '*': + return make_token(TokenType::Star); + case '/': + return make_token(TokenType::Slash); + case '%': + return make_token(TokenType::Percent); + case '>': + return make_token(match('=') ? TokenType::GreaterEqual : TokenType::Greater); + case '<': + return make_token(match('=') ? TokenType::LessEqual : TokenType::Less); + case '?': + return make_token(TokenType::Question); + case ':': + return make_token(TokenType::Colon); + case '.': + return make_token(TokenType::Dot); + case ';': + return make_token(TokenType::Semicolon); + case ',': + return make_token(TokenType::Comma); + case '@': + return make_token(TokenType::At); + case '"': + return scan_string(); + case '\'': + return scan_char(); + case '(': + return make_token(TokenType::LParen); + case ')': + return make_token(TokenType::RParen); + case '{': + return make_token(TokenType::LBrace); + case '}': + return make_token(TokenType::RBrace); + case '[': + return make_token(TokenType::LBracket); + case ']': + return make_token(TokenType::RBracket); + default: + return make_token(TokenType::Unknown); } +} - Token Lexer::scanToken() { - char c = advance(); - - // Fast paths for common leading characters - if (std::isdigit(static_cast(c))) - return scanNumber(); - if (std::isalpha(static_cast(c)) || c == '_') - return scanIdentifierOrKeyword(); - - switch (c) { - case '=': - return match('=') ? makeToken(TokenType::EqualEqual, "==") - : makeToken(TokenType::Equals, "="); - case '!': - return match('=') ? makeToken(TokenType::BangEqual, "!=") - : makeToken(TokenType::Bang, "!"); - case '+': - return match('+') ? makeToken(TokenType::PlusPlus, "++") - : makeToken(TokenType::Plus, "+"); - case '&': - return match('&') ? makeToken(TokenType::AmpersandAmpersand, "&&") - : makeToken(TokenType::Ampersand, "&"); - case '|': - return match('|') ? makeToken(TokenType::PipePipe, "||") - : makeToken(TokenType::Pipe, "|"); - case '^': - return makeToken(TokenType::Caret, "^"); - case '~': - return makeToken(TokenType::Tilde, "~"); - case '-': - if (match('>')) - return makeToken(TokenType::Arrow, "->"); - return match('-') ? makeToken(TokenType::MinusMinus, "--") - : makeToken(TokenType::Minus, "-"); - case '*': - return makeToken(TokenType::Star, "*"); - case '/': - return makeToken(TokenType::Slash, "/"); - case '%': - return makeToken(TokenType::Percent, "%"); - case '>': - return match('=') ? makeToken(TokenType::GreaterEqual, ">=") - : makeToken(TokenType::Greater, ">"); - case '<': - return match('=') ? makeToken(TokenType::LessEqual, "<=") - : makeToken(TokenType::Less, "<"); - case '?': - return makeToken(TokenType::Question, "?"); - case ':': - return makeToken(TokenType::Colon, ":"); - case '.': - return makeToken(TokenType::Dot, "."); - case ';': - return makeToken(TokenType::Semicolon, ";"); - case ',': - return makeToken(TokenType::Comma, ","); - case '@': - return makeToken(TokenType::At, "@"); - case '"': - return scanString(); - case '\'': - return scanChar(); - case '(': - return makeToken(TokenType::LParen, "("); - case ')': - return makeToken(TokenType::RParen, ")"); - case '{': - return makeToken(TokenType::LBrace, "{"); - case '}': - return makeToken(TokenType::RBrace, "}"); - case '[': - return makeToken(TokenType::LBracket, "["); - case ']': - return makeToken(TokenType::RBracket, "]"); - default: - return makeToken(TokenType::Unknown, std::string(1, c)); - } +Token Lexer::scan_number() { + while (is_digit(peek())) { + advance(); } - Token Lexer::scanNumber() { - // Integers by default; a trailing '.f' upgrades to float, - // and a trailing 'b' turns a 0/1 into a bit literal. - size_t start = m_position - 1; - while (std::isdigit(static_cast(peek()))) (void)advance(); - - if (peek() == '.') { - (void)advance(); - while (std::isdigit(static_cast(peek()))) (void)advance(); - if (peek() == 'f') { - (void)advance(); - return makeToken(TokenType::FloatLiteral, - std::string(m_source.substr(start, m_position - start))); - } else { - reportError("float literals must end with 'f'"); - return makeToken(TokenType::Unknown, - std::string(m_source.substr(start, m_position - start))); - } + if (peek() == '.') { + advance(); + while (is_digit(peek())) { + advance(); } - // Support integer part followed directly by 'f' (e.g., 3f) if (peek() == 'f') { - (void)advance(); - return makeToken(TokenType::FloatLiteral, - std::string(m_source.substr(start, m_position - start))); + advance(); + return make_token(TokenType::FloatLiteral); } - if (peek() == 'L') { - (void)advance(); - return makeToken(TokenType::LongLiteral, - std::string(m_source.substr(start, m_position - start))); - } + report_error("float literals must end with 'f'"); + } - if (peek() == 'b') { - std::string_view digits = m_source.substr(start, m_position - start); - if (digits != "0" && digits != "1") { - reportError("bit literals must be 0b or 1b"); - (void)advance(); - return makeToken(TokenType::Unknown, - std::string(m_source.substr(start, m_position - start))); - } - (void)advance(); - return makeToken(TokenType::BitLiteral, - std::string(m_source.substr(start, m_position - start))); - } + if (peek() == 'f') { + advance(); + return make_token(TokenType::FloatLiteral); + } - return makeToken(TokenType::IntegerLiteral, - std::string(m_source.substr(start, m_position - start))); + if (peek() == 'L') { + advance(); + return make_token(TokenType::LongLiteral); } - Token Lexer::scanIdentifierOrKeyword() { - // Identifiers are [A-Za-z_][A-Za-z0-9_]*. Some of them are keywords. - size_t start = m_position - 1; - while (std::isalnum(static_cast(peek())) || peek() == '_') (void)advance(); - - std::string_view text = m_source.substr(start, m_position - start); - - static const std::unordered_map keywords = { - - // Primitives - {"null", TokenType::Null}, - {"int", TokenType::Int}, - {"long", TokenType::Long}, - {"float", TokenType::Float}, - {"string", TokenType::String}, - {"char", TokenType::Char}, - {"qubit", TokenType::Qubit}, - {"bit", TokenType::Bit}, - {"boolean", TokenType::Boolean}, - - // Boolean literals (treated as keywords for convenience) - {"true", TokenType::True}, - {"false", TokenType::False}, - - // Keywords - {"void", TokenType::Void}, - {"function", TokenType::Function}, - {"return", TokenType::Return}, - {"if", TokenType::If}, - {"else", TokenType::Else}, - {"for", TokenType::For}, - {"while", TokenType::While}, - {"measure", TokenType::Measure}, - {"final", TokenType::Final}, - {"reset", TokenType::Reset}, - {"default", TokenType::Default}, - - // Annotation Values - {"quantum", TokenType::Quantum}, - {"tracked", TokenType::Tracked}, - {"shots", TokenType::Shots}, - - // Class System - {"class", TokenType::Class}, - {"public", TokenType::Public}, - {"private", TokenType::Private}, - {"protected", TokenType::Protected}, - {"static", TokenType::Static}, - {"extends", TokenType::Extends}, - {"abstract", TokenType::Abstract}, - {"virtual", TokenType::Virtual}, - {"override", TokenType::Override}, - {"super", TokenType::Super}, - {"this", TokenType::This}, - {"import", TokenType::Import}, - {"package", TokenType::Package}, - {"new", TokenType::New}, - {"constructor", TokenType::Constructor}, - {"destructor", TokenType::Destructor}, - {"destroy", TokenType::Destroy}, - - // Built ins - {"echo", TokenType::Echo}}; - - auto it = keywords.find(text); - if (it != keywords.end()) { - return makeToken(it->second, std::string(text)); + if (peek() == 'b') { + const auto digits = source_.substr(token_start_, position_ - token_start_); + if (digits != "0" && digits != "1") { + report_error("bit literals must be 0b or 1b"); } - return makeToken(TokenType::Identifier, std::string(text)); + advance(); + return make_token(TokenType::BitLiteral); } - Token Lexer::scanString() { - // Strings are double-quoted and may span lines; we do not process escapes yet. - size_t start = m_position; - while (m_position < m_source.size() && peek() != '"') { - if (peek() == '\n') - m_line++; - (void)advance(); - } + return make_token(TokenType::IntegerLiteral); +} - if (peek() == '"') { - (void)advance(); - return makeToken(TokenType::StringLiteral, - std::string(m_source.substr(start - 1, m_position - start + 1))); - } +Token Lexer::scan_identifier_or_keyword() { + while (is_alphanumeric(peek())) { + advance(); + } + + const auto identifier = source_.substr(token_start_, position_ - token_start_); + const auto type = keyword_type(identifier).value_or(TokenType::Identifier); + return make_token(type); +} + +Token Lexer::scan_string() { + while (!is_at_end() && peek() != '"') { + advance(); + } - reportError("unterminated string literal"); - return makeToken(TokenType::Unknown, - std::string(m_source.substr(start - 1, m_position - start + 1))); + if (is_at_end()) { + report_error("unterminated string literal"); } - Token Lexer::scanChar() { - // Char literals are simple: '\'' X '\'' with no escaping support for now. - size_t start = m_position; - if (m_position < m_source.size()) - (void)advance(); + advance(); + return make_token(TokenType::StringLiteral); +} - if (peek() == '\'') { - (void)advance(); - return makeToken(TokenType::CharLiteral, std::string(m_source.substr(start - 1, 3))); - } +Token Lexer::scan_char() { + if (!is_at_end()) { + advance(); + } - reportError("unterminated char literal"); - return makeToken(TokenType::Unknown, - std::string(m_source.substr(start - 1, m_position - start + 1))); + if (peek() == '\'') { + advance(); + return make_token(TokenType::CharLiteral); } + + report_error("unterminated char literal"); +} + } // namespace bloch::compiler diff --git a/src/bloch/compiler/lexer/lexer.hpp b/src/bloch/compiler/lexer/lexer.hpp index 4f40a00..c098072 100644 --- a/src/bloch/compiler/lexer/lexer.hpp +++ b/src/bloch/compiler/lexer/lexer.hpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,44 +14,47 @@ #pragma once -#include +#include #include #include + #include "bloch/compiler/lexer/token.hpp" -#include "bloch/support/error/bloch_error.hpp" namespace bloch::compiler { - // The Lexer turns raw source into a flat stream of tokens. - // It is intentionally simple: single-pass, no backtracking, and - // only enough lookahead for two-character operators and // comments. - class Lexer { - public: - explicit Lexer(const std::string_view source) noexcept; - [[nodiscard]] std::vector tokenize(); - - private: - std::string_view m_source; - size_t m_position; - int m_line; - int m_column; - - // Character helpers - [[nodiscard]] char peek() const noexcept; - [[nodiscard]] char peekNext() const noexcept; - [[nodiscard]] char advance() noexcept; - [[nodiscard]] bool match(char expected) noexcept; - - // Trivia and errors - void skipWhitespace(); - void skipComment(); - [[noreturn]] void reportError(const std::string& msg); - - // Token producers - [[nodiscard]] Token makeToken(TokenType type, const std::string& value); - [[nodiscard]] Token scanToken(); - [[nodiscard]] Token scanNumber(); - [[nodiscard]] Token scanIdentifierOrKeyword(); - [[nodiscard]] Token scanString(); - [[nodiscard]] Token scanChar(); - }; + +// Converts source text into a flat token stream in a single pass. The source must outlive the +// lexer because it is retained as a non-owning view. +class Lexer { + public: + explicit Lexer(std::string_view source) noexcept; + + [[nodiscard]] std::vector tokenize(); + + private: + std::string_view source_; + std::size_t position_ = 0; + std::size_t token_start_ = 0; + int line_ = 1; + int column_ = 1; + int token_line_ = 1; + int token_column_ = 1; + + [[nodiscard]] bool is_at_end() const noexcept; + [[nodiscard]] char peek() const noexcept; + [[nodiscard]] char peek_next() const noexcept; + char advance() noexcept; + [[nodiscard]] bool match(char expected) noexcept; + + void skip_whitespace() noexcept; + void skip_comment() noexcept; + [[noreturn]] void report_error(std::string_view message) const; + + [[nodiscard]] Token make_token(TokenType type) const; + [[nodiscard]] Token scan_token(); + [[nodiscard]] Token scan_number(); + [[nodiscard]] Token scan_identifier_or_keyword(); + [[nodiscard]] Token scan_string(); + [[nodiscard]] Token scan_char(); +}; + } // namespace bloch::compiler diff --git a/src/bloch/compiler/lexer/token.hpp b/src/bloch/compiler/lexer/token.hpp index 0cfd87c..3f7b205 100644 --- a/src/bloch/compiler/lexer/token.hpp +++ b/src/bloch/compiler/lexer/token.hpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,118 +17,118 @@ #include namespace bloch::compiler { - // Tokens represent the smallest meaningful pieces the parser understands. - // We group them loosely by purpose to keep scanning and parsing readable. - enum class TokenType { - // Literals - Identifier, - IntegerLiteral, - FloatLiteral, - LongLiteral, - BitLiteral, - StringLiteral, - CharLiteral, +// Tokens represent the smallest meaningful pieces the parser understands. +// We group them loosely by purpose to keep scanning and parsing readable. +enum class TokenType { + // Literals + Identifier, + IntegerLiteral, + FloatLiteral, + LongLiteral, + BitLiteral, + StringLiteral, + CharLiteral, - // Boolean literals - True, - False, + // Boolean literals + True, + False, - // Keywords - Null, - Int, - Long, - Float, - String, - Char, - Qubit, - Bit, - Boolean, - Void, - Function, - Return, - If, - Else, - For, - While, - Measure, - Final, - Reset, - Default, + // Keywords + Null, + Int, + Long, + Float, + String, + Char, + Qubit, + Bit, + Boolean, + Void, + Function, + Return, + If, + Else, + For, + While, + Measure, + Final, + Reset, + Default, - // Annotations - At, - Quantum, - Tracked, - Shots, + // Annotations + At, + Quantum, + Tracked, + Shots, - // Class System - Class, - Public, - Private, - Protected, - Static, - Extends, - Abstract, - Virtual, - Override, - Super, - This, - Import, - Package, - New, - Constructor, - Destructor, - Destroy, + // Class System + Class, + Public, + Private, + Protected, + Static, + Extends, + Abstract, + Virtual, + Override, + Super, + This, + Import, + Package, + New, + Constructor, + Destructor, + Destroy, - // Operators and Punctuation - Equals, - Plus, - PlusPlus, - Minus, - MinusMinus, - Star, - Slash, - Percent, - Greater, - GreaterEqual, - Less, - LessEqual, - EqualEqual, - Bang, - BangEqual, - Ampersand, - AmpersandAmpersand, - Pipe, - PipePipe, - Caret, - Tilde, - Question, - Colon, - Dot, - Semicolon, - Comma, - Arrow, - LParen, - RParen, - LBrace, - RBrace, - LBracket, - RBracket, + // Operators and Punctuation + Equals, + Plus, + PlusPlus, + Minus, + MinusMinus, + Star, + Slash, + Percent, + Greater, + GreaterEqual, + Less, + LessEqual, + EqualEqual, + Bang, + BangEqual, + Ampersand, + AmpersandAmpersand, + Pipe, + PipePipe, + Caret, + Tilde, + Question, + Colon, + Dot, + Semicolon, + Comma, + Arrow, + LParen, + RParen, + LBrace, + RBrace, + LBracket, + RBracket, - // Built-ins - Echo, + // Built-ins + Echo, - // Control - Eof, - Unknown - }; + // Control + Eof, + Unknown +}; - // A token carries what it is, the raw text we saw, and where it came from. - // Line/column are 1-based and point to the start of the token for friendly errors. - struct Token { - TokenType type; - std::string value; - int line; - int column; - }; +// A token carries what it is, the raw text we saw, and where it came from. +// Line/column are 1-based and point to the start of the token for friendly errors. +struct Token { + TokenType type; + std::string value; + int line; + int column; +}; } // namespace bloch::compiler diff --git a/src/bloch/compiler/parser/parser.cpp b/src/bloch/compiler/parser/parser.cpp index 8b74836..24a2a85 100644 --- a/src/bloch/compiler/parser/parser.cpp +++ b/src/bloch/compiler/parser/parser.cpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,1714 +23,1707 @@ namespace bloch::compiler { - using support::BlochError; - using support::ErrorCategory; - Parser::Parser(std::vector tokens) : m_tokens(std::move(tokens)), m_current(0) {} - - // Token manipulation - const Token& Parser::peek() const { - if (m_current >= m_tokens.size()) - return m_tokens.back(); - return m_tokens[m_current]; - } - const Token& Parser::previous() const { return m_tokens[m_current - 1]; } - const Token& Parser::advance() { - if (!isAtEnd()) - m_current++; - return previous(); - } - const Token& Parser::expect(TokenType type, const std::string& message) { - if (check(type)) - return advance(); - reportError(message); - return peek(); - } - - // Token matching - bool Parser::match(TokenType type) { - if (check(type)) { - (void)advance(); - return true; - } - return false; - } - bool Parser::check(TokenType type) const { - if (isAtEnd()) - return false; - return peek().type == type; - } - bool Parser::checkNext(TokenType type) const { - if (m_current + 1 >= m_tokens.size()) - return false; - return m_tokens[m_current + 1].type == type; - } - bool Parser::checkFunctionAnnotation() const { - if (!check(TokenType::At)) - return false; - if (!checkNext(TokenType::Quantum) && !checkNext(TokenType::Shots)) - return false; +using support::BlochError; +using support::ErrorCategory; +Parser::Parser(std::vector tokens) : m_tokens(std::move(tokens)), m_current(0) {} + +// Token manipulation +const Token& Parser::peek() const { + if (m_current >= m_tokens.size()) + return m_tokens.back(); + return m_tokens[m_current]; +} +const Token& Parser::previous() const { return m_tokens[m_current - 1]; } +const Token& Parser::advance() { + if (!isAtEnd()) + m_current++; + return previous(); +} +const Token& Parser::expect(TokenType type, const std::string& message) { + if (check(type)) + return advance(); + reportError(message); + return peek(); +} + +// Token matching +bool Parser::match(TokenType type) { + if (check(type)) { + (void)advance(); return true; } + return false; +} +bool Parser::check(TokenType type) const { + if (isAtEnd()) + return false; + return peek().type == type; +} +bool Parser::checkNext(TokenType type) const { + if (m_current + 1 >= m_tokens.size()) + return false; + return m_tokens[m_current + 1].type == type; +} +bool Parser::checkFunctionAnnotation() const { + if (!check(TokenType::At)) + return false; + if (!checkNext(TokenType::Quantum) && !checkNext(TokenType::Shots)) + return false; + return true; +} - bool Parser::isTypeAhead() const { - if (check(TokenType::Void) || check(TokenType::Int) || check(TokenType::Float) || - check(TokenType::Long) || check(TokenType::Char) || check(TokenType::String) || - check(TokenType::Bit) || check(TokenType::Qubit) || check(TokenType::Boolean)) { - return true; - } - if (!check(TokenType::Identifier)) - return false; - size_t idx = m_current; // start at identifier - // Consume dotted qualifiers - while (idx + 2 < m_tokens.size() && m_tokens[idx + 1].type == TokenType::Dot && - m_tokens[idx + 2].type == TokenType::Identifier) { - idx += 2; - } - // Skip generic type arguments if present: < ... > - auto skipTypeArgs = [&](size_t& i) { - if (i + 1 >= m_tokens.size() || m_tokens[i + 1].type != TokenType::Less) - return; - int depth = 0; - size_t j = i + 1; - while (j < m_tokens.size()) { - if (m_tokens[j].type == TokenType::Less) - depth++; - else if (m_tokens[j].type == TokenType::Greater) { - depth--; - if (depth == 0) { - i = j; - break; - } +bool Parser::isTypeAhead() const { + if (check(TokenType::Void) || check(TokenType::Int) || check(TokenType::Float) || + check(TokenType::Long) || check(TokenType::Char) || check(TokenType::String) || + check(TokenType::Bit) || check(TokenType::Qubit) || check(TokenType::Boolean)) { + return true; + } + if (!check(TokenType::Identifier)) + return false; + size_t idx = m_current; // start at identifier + // Consume dotted qualifiers + while (idx + 2 < m_tokens.size() && m_tokens[idx + 1].type == TokenType::Dot && + m_tokens[idx + 2].type == TokenType::Identifier) { + idx += 2; + } + // Skip generic type arguments if present: < ... > + auto skipTypeArgs = [&](size_t& i) { + if (i + 1 >= m_tokens.size() || m_tokens[i + 1].type != TokenType::Less) + return; + int depth = 0; + size_t j = i + 1; + while (j < m_tokens.size()) { + if (m_tokens[j].type == TokenType::Less) + depth++; + else if (m_tokens[j].type == TokenType::Greater) { + depth--; + if (depth == 0) { + i = j; + break; } - j++; - } - }; - skipTypeArgs(idx); - if (idx + 1 >= m_tokens.size()) - return false; - TokenType afterName = m_tokens[idx + 1].type; - if (afterName == TokenType::Identifier) { - return true; // Type Name varName - } - if (afterName == TokenType::LBracket) { - size_t j = idx + 2; - while (j < m_tokens.size() && m_tokens[j].type != TokenType::RBracket) { - // Bail out on statement terminators to avoid misclassifying expressions - if (m_tokens[j].type == TokenType::Semicolon || m_tokens[j].type == TokenType::Eof) - return false; - ++j; - } - if (j >= m_tokens.size() || m_tokens[j].type != TokenType::RBracket) - return false; - if (j + 1 < m_tokens.size() && m_tokens[j + 1].type == TokenType::Identifier) { - return true; // Type[] varName } + j++; } + }; + skipTypeArgs(idx); + if (idx + 1 >= m_tokens.size()) return false; + TokenType afterName = m_tokens[idx + 1].type; + if (afterName == TokenType::Identifier) { + return true; // Type Name varName } - - bool Parser::isAtEnd() const { return peek().type == TokenType::Eof; } - - // Error - void Parser::reportError(const std::string& msg) { - const Token& token = peek(); - throw BlochError(ErrorCategory::Parse, token.line, token.column, msg); + if (afterName == TokenType::LBracket) { + size_t j = idx + 2; + while (j < m_tokens.size() && m_tokens[j].type != TokenType::RBracket) { + // Bail out on statement terminators to avoid misclassifying expressions + if (m_tokens[j].type == TokenType::Semicolon || m_tokens[j].type == TokenType::Eof) + return false; + ++j; + } + if (j >= m_tokens.size() || m_tokens[j].type != TokenType::RBracket) + return false; + if (j + 1 < m_tokens.size() && m_tokens[j + 1].type == TokenType::Identifier) { + return true; // Type[] varName + } } - - // Main parse function - std::unique_ptr Parser::parse() { - std::unique_ptr program = std::make_unique(); - bool seenPackage = false; - bool seenTopLevelDeclaration = false; - - // Package (optional, at most one) and imports (zero or more) must appear - // before any other top-level declarations/statements. - while (!isAtEnd()) { - if (!seenTopLevelDeclaration && match(TokenType::Package)) { - if (seenPackage) { - reportError("Only one package declaration is allowed per file"); - } - program->packageDecl = parsePackageDeclaration(); - seenPackage = true; - continue; + return false; +} + +bool Parser::isAtEnd() const { return peek().type == TokenType::Eof; } + +// Error +void Parser::reportError(const std::string& msg) { + const Token& token = peek(); + throw BlochError(ErrorCategory::Parse, token.line, token.column, msg); +} + +// Main parse function +std::unique_ptr Parser::parse() { + std::unique_ptr program = std::make_unique(); + bool seenPackage = false; + bool seenTopLevelDeclaration = false; + + // Package (optional, at most one) and imports (zero or more) must appear + // before any other top-level declarations/statements. + while (!isAtEnd()) { + if (!seenTopLevelDeclaration && match(TokenType::Package)) { + if (seenPackage) { + reportError("Only one package declaration is allowed per file"); } + program->packageDecl = parsePackageDeclaration(); + seenPackage = true; + continue; + } - if (!seenTopLevelDeclaration && match(TokenType::Import)) { - program->imports.push_back(parseImport()); - continue; - } + if (!seenTopLevelDeclaration && match(TokenType::Import)) { + program->imports.push_back(parseImport()); + continue; + } - // From here on we are in the "body" of the file; no more package/imports allowed. - seenTopLevelDeclaration = true; + // From here on we are in the "body" of the file; no more package/imports allowed. + seenTopLevelDeclaration = true; - if (check(TokenType::Static) || check(TokenType::Abstract) || check(TokenType::Class)) { - program->classes.push_back(parseClassDeclaration()); - } else if (check(TokenType::Function) || checkFunctionAnnotation()) { - program->functions.push_back(parseFunction()); - } else { - program->statements.push_back(parseStatement()); - flushExtraStatements(program->statements); - } + if (check(TokenType::Static) || check(TokenType::Abstract) || check(TokenType::Class)) { + program->classes.push_back(parseClassDeclaration()); + } else if (check(TokenType::Function) || checkFunctionAnnotation()) { + program->functions.push_back(parseFunction()); + } else { + program->statements.push_back(parseStatement()); + flushExtraStatements(program->statements); } - - return program; } - // Top level - - std::unique_ptr Parser::parsePackageDeclaration() { - std::unique_ptr pkg = std::make_unique(); - const Token& pkgTok = previous(); - pkg->line = pkgTok.line; - pkg->column = pkgTok.column; - pkg->nameParts = parseQualifiedName(); - (void)expect(TokenType::Semicolon, "Expected ';' after package declaration"); - return pkg; + return program; +} + +// Top level + +std::unique_ptr Parser::parsePackageDeclaration() { + std::unique_ptr pkg = std::make_unique(); + const Token& pkgTok = previous(); + pkg->line = pkgTok.line; + pkg->column = pkgTok.column; + pkg->nameParts = parseQualifiedName(); + (void)expect(TokenType::Semicolon, "Expected ';' after package declaration"); + return pkg; +} + +std::unique_ptr Parser::parseImport() { + std::unique_ptr import = std::make_unique(); + const Token& importTok = previous(); + import->line = importTok.line; + import->column = importTok.column; + + std::vector parts; + const Token& first = expect(TokenType::Identifier, "Expected identifier after 'import'"); + parts.push_back(first.value); + + bool isWildcard = false; + while (match(TokenType::Dot)) { + if (match(TokenType::Star)) { + isWildcard = true; + break; + } + const Token& part = expect(TokenType::Identifier, "Expected identifier after '.'"); + parts.push_back(part.value); } - std::unique_ptr Parser::parseImport() { - std::unique_ptr import = std::make_unique(); - const Token& importTok = previous(); - import->line = importTok.line; - import->column = importTok.column; - - std::vector parts; - const Token& first = expect(TokenType::Identifier, "Expected identifier after 'import'"); - parts.push_back(first.value); - - bool isWildcard = false; - while (match(TokenType::Dot)) { - if (match(TokenType::Star)) { - isWildcard = true; - break; - } - const Token& part = expect(TokenType::Identifier, "Expected identifier after '.'"); - parts.push_back(part.value); + if (isWildcard) { + import->packageParts = std::move(parts); + import->isWildcard = true; + } else { + if (parts.empty()) { + reportError("Expected identifier after 'import'"); } - - if (isWildcard) { - import->packageParts = std::move(parts); - import->isWildcard = true; + if (parts.size() == 1) { + import->symbol = parts[0]; } else { - if (parts.empty()) { - reportError("Expected identifier after 'import'"); - } - if (parts.size() == 1) { - import->symbol = parts[0]; - } else { - import->symbol = parts.back(); - parts.pop_back(); - import->packageParts = std::move(parts); - } + import->symbol = parts.back(); + parts.pop_back(); + import->packageParts = std::move(parts); } - - (void)expect(TokenType::Semicolon, "Expected ';' after import statement"); - return import; } - std::unique_ptr Parser::parseClassDeclaration() { - bool isStatic = false; - bool isAbstract = false; - while (true) { - if (match(TokenType::Static)) { - if (isStatic) - reportError("duplicate 'static' modifier on class"); - isStatic = true; - continue; - } - if (match(TokenType::Abstract)) { - if (isAbstract) - reportError("duplicate 'abstract' modifier on class"); - isAbstract = true; - continue; - } - break; - } + (void)expect(TokenType::Semicolon, "Expected ';' after import statement"); + return import; +} + +std::unique_ptr Parser::parseClassDeclaration() { + bool isStatic = false; + bool isAbstract = false; + while (true) { + if (match(TokenType::Static)) { + if (isStatic) + reportError("duplicate 'static' modifier on class"); + isStatic = true; + continue; + } + if (match(TokenType::Abstract)) { + if (isAbstract) + reportError("duplicate 'abstract' modifier on class"); + isAbstract = true; + continue; + } + break; + } - (void)expect(TokenType::Class, "Expected 'class' keyword"); + (void)expect(TokenType::Class, "Expected 'class' keyword"); - const Token& nameTok = expect(TokenType::Identifier, "Expected class name after 'class'"); + const Token& nameTok = expect(TokenType::Identifier, "Expected class name after 'class'"); - std::unique_ptr cls = std::make_unique(); - cls->name = nameTok.value; - cls->line = nameTok.line; - cls->column = nameTok.column; - cls->isStatic = isStatic; - cls->isAbstract = isAbstract; + std::unique_ptr cls = std::make_unique(); + cls->name = nameTok.value; + cls->line = nameTok.line; + cls->column = nameTok.column; + cls->isStatic = isStatic; + cls->isAbstract = isAbstract; - if (check(TokenType::Less)) { - cls->typeParameters = parseTypeParameters(); - } + if (check(TokenType::Less)) { + cls->typeParameters = parseTypeParameters(); + } - if (match(TokenType::Extends)) { - auto baseTy = parseType(); - if (!baseTy) - reportError("Expected base class name after 'extends'"); - if (!dynamic_cast(baseTy.get())) { - reportError("Base class must be a named type"); - } - cls->baseType = std::move(baseTy); - if (auto named = dynamic_cast(cls->baseType.get())) - cls->baseName = named->nameParts; - if (check(TokenType::Extends)) { - reportError("Only single inheritance is supported"); - } + if (match(TokenType::Extends)) { + auto baseTy = parseType(); + if (!baseTy) + reportError("Expected base class name after 'extends'"); + if (!dynamic_cast(baseTy.get())) { + reportError("Base class must be a named type"); } - - (void)expect(TokenType::LBrace, "Expected '{' to start class body"); - while (!check(TokenType::RBrace) && !isAtEnd()) { - std::unique_ptr member = parseClassMember(cls->name, cls->isStatic); - if (member) - cls->members.push_back(std::move(member)); + cls->baseType = std::move(baseTy); + if (auto named = dynamic_cast(cls->baseType.get())) + cls->baseName = named->nameParts; + if (check(TokenType::Extends)) { + reportError("Only single inheritance is supported"); } - (void)expect(TokenType::RBrace, "Expected '}' to end class body"); - - return cls; } - // Function Declaration - std::unique_ptr Parser::parseFunction() { - std::unique_ptr func = std::make_unique(); - - // Parse annotations - while (check(TokenType::At)) { - (void)previous(); - std::unique_ptr annotation = parseFunctionAnnotation(); - // TODO: Refactor this to a switch statement - if (annotation->name == "quantum") { - func->hasQuantumAnnotation = true; - } else if (annotation->name == "shots") { - func->hasShotsAnnotation = true; - } else { - reportError("Invalid annotation name"); - } - func->annotations.push_back(std::move(annotation)); + (void)expect(TokenType::LBrace, "Expected '{' to start class body"); + while (!check(TokenType::RBrace) && !isAtEnd()) { + std::unique_ptr member = parseClassMember(cls->name, cls->isStatic); + if (member) + cls->members.push_back(std::move(member)); + } + (void)expect(TokenType::RBrace, "Expected '}' to end class body"); + + return cls; +} + +// Function Declaration +std::unique_ptr Parser::parseFunction() { + std::unique_ptr func = std::make_unique(); + + // Parse annotations + while (check(TokenType::At)) { + (void)previous(); + std::unique_ptr annotation = parseFunctionAnnotation(); + // TODO: Refactor this to a switch statement + if (annotation->name == "quantum") { + func->hasQuantumAnnotation = true; + } else if (annotation->name == "shots") { + func->hasShotsAnnotation = true; + } else { + reportError("Invalid annotation name"); } + func->annotations.push_back(std::move(annotation)); + } - (void)expect(TokenType::Function, "Expected 'function' keyword"); + (void)expect(TokenType::Function, "Expected 'function' keyword"); - if (!check(TokenType::Identifier)) { - reportError("Expected function name after 'function' keyword"); - } - const Token& nameToken = advance(); - func->name = nameToken.value; - func->line = nameToken.line; - func->column = nameToken.column; + if (!check(TokenType::Identifier)) { + reportError("Expected function name after 'function' keyword"); + } + const Token& nameToken = advance(); + func->name = nameToken.value; + func->line = nameToken.line; + func->column = nameToken.column; - // Parse parameters - (void)expect(TokenType::LParen, "Expected '(' after function name"); - while (!check(TokenType::RParen)) { - std::unique_ptr param = std::make_unique(); + // Parse parameters + (void)expect(TokenType::LParen, "Expected '(' after function name"); + while (!check(TokenType::RParen)) { + std::unique_ptr param = std::make_unique(); - param->type = parseType(); + param->type = parseType(); - const Token& paramToken = expect(TokenType::Identifier, "Expected parameter name"); - param->name = paramToken.value; - param->line = paramToken.line; - param->column = paramToken.column; + const Token& paramToken = expect(TokenType::Identifier, "Expected parameter name"); + param->name = paramToken.value; + param->line = paramToken.line; + param->column = paramToken.column; - func->params.push_back(std::move(param)); + func->params.push_back(std::move(param)); - if (!match(TokenType::Comma)) - break; - } - (void)expect(TokenType::RParen, "Expected ')' after parameters"); + if (!match(TokenType::Comma)) + break; + } + (void)expect(TokenType::RParen, "Expected ')' after parameters"); - // Return type - (void)expect(TokenType::Arrow, "Expected '->' before return type"); + // Return type + (void)expect(TokenType::Arrow, "Expected '->' before return type"); - func->returnType = parseType(); + func->returnType = parseType(); - // Body - func->body = parseBlock(); + // Body + func->body = parseBlock(); - return func; - } + return func; +} - Visibility Parser::parseVisibility() { - if (match(TokenType::Public)) - return Visibility::Public; - if (match(TokenType::Private)) - return Visibility::Private; - if (match(TokenType::Protected)) - return Visibility::Protected; +Visibility Parser::parseVisibility() { + if (match(TokenType::Public)) return Visibility::Public; + if (match(TokenType::Private)) + return Visibility::Private; + if (match(TokenType::Protected)) + return Visibility::Protected; + return Visibility::Public; +} + +std::vector Parser::parseQualifiedName() { + std::vector parts; + const Token& first = expect(TokenType::Identifier, "Expected identifier"); + parts.push_back(first.value); + while (match(TokenType::Dot)) { + const Token& part = expect(TokenType::Identifier, "Expected identifier after '.'"); + parts.push_back(part.value); } - - std::vector Parser::parseQualifiedName() { - std::vector parts; - const Token& first = expect(TokenType::Identifier, "Expected identifier"); - parts.push_back(first.value); - while (match(TokenType::Dot)) { - const Token& part = expect(TokenType::Identifier, "Expected identifier after '.'"); - parts.push_back(part.value); - } - return parts; + return parts; +} + +std::unique_ptr Parser::parseClassMember(const std::string& className, + bool isStaticClass) { + std::vector> annotations = parseAnnotations(); + + bool hasVisibility = + check(TokenType::Public) || check(TokenType::Private) || check(TokenType::Protected); + Visibility visibility = hasVisibility + ? parseVisibility() + : (isStaticClass ? Visibility::Public : Visibility::Private); + if (hasVisibility && + (check(TokenType::Public) || check(TokenType::Private) || check(TokenType::Protected))) { + reportError("Multiple visibility modifiers are not allowed on class members"); } - std::unique_ptr Parser::parseClassMember(const std::string& className, - bool isStaticClass) { - std::vector> annotations = parseAnnotations(); - - bool hasVisibility = - check(TokenType::Public) || check(TokenType::Private) || check(TokenType::Protected); - Visibility visibility = hasVisibility - ? parseVisibility() - : (isStaticClass ? Visibility::Public : Visibility::Private); - if (hasVisibility && (check(TokenType::Public) || check(TokenType::Private) || - check(TokenType::Protected))) { - reportError("Multiple visibility modifiers are not allowed on class members"); - } - - bool isStatic = false; - bool isVirtual = false; - bool isOverride = false; - bool scanningModifiers = true; - while (scanningModifiers) { - if (match(TokenType::Static)) { - if (isStatic) - reportError("Duplicate 'static' modifier"); - isStatic = true; - continue; - } - if (match(TokenType::Virtual)) { - if (isVirtual) - reportError("Duplicate 'virtual' modifier"); - isVirtual = true; - continue; - } - if (match(TokenType::Override)) { - if (isOverride) - reportError("Duplicate 'override' modifier"); - isOverride = true; - continue; - } - scanningModifiers = false; - } + bool isStatic = false; + bool isVirtual = false; + bool isOverride = false; + bool scanningModifiers = true; + while (scanningModifiers) { + if (match(TokenType::Static)) { + if (isStatic) + reportError("Duplicate 'static' modifier"); + isStatic = true; + continue; + } + if (match(TokenType::Virtual)) { + if (isVirtual) + reportError("Duplicate 'virtual' modifier"); + isVirtual = true; + continue; + } + if (match(TokenType::Override)) { + if (isOverride) + reportError("Duplicate 'override' modifier"); + isOverride = true; + continue; + } + scanningModifiers = false; + } - std::vector> trailingAnnotations = parseAnnotations(); - for (auto& ann : trailingAnnotations) annotations.push_back(std::move(ann)); + std::vector> trailingAnnotations = parseAnnotations(); + for (auto& ann : trailingAnnotations) + annotations.push_back(std::move(ann)); - if (match(TokenType::Constructor)) { - if (!annotations.empty()) { - reportError("Annotations are not allowed on constructors"); - } - if (isStaticClass) - reportError("Static classes cannot declare constructors"); - if (isStatic || isVirtual || isOverride) - reportError("Constructors cannot be static, virtual, or override"); - return parseConstructorDeclaration(visibility, className); + if (match(TokenType::Constructor)) { + if (!annotations.empty()) { + reportError("Annotations are not allowed on constructors"); } + if (isStaticClass) + reportError("Static classes cannot declare constructors"); + if (isStatic || isVirtual || isOverride) + reportError("Constructors cannot be static, virtual, or override"); + return parseConstructorDeclaration(visibility, className); + } - if (match(TokenType::Destructor)) { - if (!annotations.empty()) { - reportError("Annotations are not allowed on destructors"); - } - if (isStaticClass) - reportError("Static classes cannot declare destructors"); - if (isStatic || isVirtual || isOverride) - reportError("Destructors cannot be static, virtual, or override"); - return parseDestructorDeclaration(visibility); + if (match(TokenType::Destructor)) { + if (!annotations.empty()) { + reportError("Annotations are not allowed on destructors"); } + if (isStaticClass) + reportError("Static classes cannot declare destructors"); + if (isStatic || isVirtual || isOverride) + reportError("Destructors cannot be static, virtual, or override"); + return parseDestructorDeclaration(visibility); + } - if (match(TokenType::Function)) { - for (const auto& annotation : annotations) { - if (annotation && annotation->name != "quantum") { - reportError("Only '@quantum' may annotate class methods"); - } - } - if (isStaticClass && !isStatic) { - reportError("Static classes may only contain static methods"); - } - if (isStaticClass && (isVirtual || isOverride)) { - reportError("Static classes cannot contain virtual or override methods"); + if (match(TokenType::Function)) { + for (const auto& annotation : annotations) { + if (annotation && annotation->name != "quantum") { + reportError("Only '@quantum' may annotate class methods"); } - return parseMethodDeclaration(visibility, isStatic, isVirtual, isOverride, - std::move(annotations)); - } - - if (isVirtual || isOverride) { - reportError("'virtual' or 'override' may only modify methods"); } if (isStaticClass && !isStatic) { - reportError("Static classes may only contain static members"); + reportError("Static classes may only contain static methods"); } - for (const auto& annotation : annotations) { - if (annotation && annotation->name != "tracked") { - reportError("Only '@tracked' may annotate class fields"); - } + if (isStaticClass && (isVirtual || isOverride)) { + reportError("Static classes cannot contain virtual or override methods"); } - - bool isFinalField = match(TokenType::Final); - return parseFieldDeclaration(visibility, isFinalField, isStatic, std::move(annotations)); + return parseMethodDeclaration(visibility, isStatic, isVirtual, isOverride, + std::move(annotations)); } - std::unique_ptr Parser::parseFieldDeclaration( - Visibility vis, bool isFinal, bool isStatic, - std::vector> annotations) { - std::unique_ptr field = std::make_unique(); - field->visibility = vis; - field->isFinal = isFinal; - field->isStatic = isStatic; - - field->annotations = std::move(annotations); - for (auto& ann : field->annotations) { - if (ann && ann->name == "tracked") - field->isTracked = true; - } - - field->fieldType = parseType(); - - const Token& nameTok = expect(TokenType::Identifier, "Expected field name"); - field->name = nameTok.value; - field->line = nameTok.line; - field->column = nameTok.column; - - if (match(TokenType::Equals)) { - field->initializer = parseExpression(); - } - - (void)expect(TokenType::Semicolon, "Expected ';' after field declaration"); - return field; - } - - std::unique_ptr Parser::parseMethodDeclaration( - Visibility vis, bool isStatic, bool isVirtual, bool isOverride, - std::vector> annotations) { - std::unique_ptr method = std::make_unique(); - method->visibility = vis; - method->isStatic = isStatic; - method->isVirtual = isVirtual; - method->isOverride = isOverride; - method->annotations = std::move(annotations); - for (auto& ann : method->annotations) { - if (ann && ann->name == "quantum") - method->hasQuantumAnnotation = true; + if (isVirtual || isOverride) { + reportError("'virtual' or 'override' may only modify methods"); + } + if (isStaticClass && !isStatic) { + reportError("Static classes may only contain static members"); + } + for (const auto& annotation : annotations) { + if (annotation && annotation->name != "tracked") { + reportError("Only '@tracked' may annotate class fields"); } + } - const Token& nameTok = expect(TokenType::Identifier, "Expected method name"); - method->name = nameTok.value; - method->line = nameTok.line; - method->column = nameTok.column; + bool isFinalField = match(TokenType::Final); + return parseFieldDeclaration(visibility, isFinalField, isStatic, std::move(annotations)); +} + +std::unique_ptr Parser::parseFieldDeclaration( + Visibility vis, bool isFinal, bool isStatic, + std::vector> annotations) { + std::unique_ptr field = std::make_unique(); + field->visibility = vis; + field->isFinal = isFinal; + field->isStatic = isStatic; + + field->annotations = std::move(annotations); + for (auto& ann : field->annotations) { + if (ann && ann->name == "tracked") + field->isTracked = true; + } - (void)expect(TokenType::LParen, "Expected '(' after method name"); - method->params = parseParameterList(); - (void)expect(TokenType::RParen, "Expected ')' after parameters"); + field->fieldType = parseType(); - (void)expect(TokenType::Arrow, "Expected '->' before return type"); - method->returnType = parseType(); + const Token& nameTok = expect(TokenType::Identifier, "Expected field name"); + field->name = nameTok.value; + field->line = nameTok.line; + field->column = nameTok.column; - if (check(TokenType::LBrace)) { - method->body = parseBlock(); - } else { - if (!method->isVirtual) { - reportError("Method must have a body unless it is marked 'virtual'"); - } - (void)expect(TokenType::Semicolon, - "Expected ';' after virtual method declaration without a body"); - method->body = nullptr; - } + if (match(TokenType::Equals)) { + field->initializer = parseExpression(); + } - return method; + (void)expect(TokenType::Semicolon, "Expected ';' after field declaration"); + return field; +} + +std::unique_ptr Parser::parseMethodDeclaration( + Visibility vis, bool isStatic, bool isVirtual, bool isOverride, + std::vector> annotations) { + std::unique_ptr method = std::make_unique(); + method->visibility = vis; + method->isStatic = isStatic; + method->isVirtual = isVirtual; + method->isOverride = isOverride; + method->annotations = std::move(annotations); + for (auto& ann : method->annotations) { + if (ann && ann->name == "quantum") + method->hasQuantumAnnotation = true; } - std::unique_ptr Parser::parseConstructorDeclaration( - Visibility vis, const std::string& className) { - std::unique_ptr ctor = std::make_unique(); - ctor->visibility = vis; - const Token& ctorTok = previous(); - ctor->line = ctorTok.line; - ctor->column = ctorTok.column; + const Token& nameTok = expect(TokenType::Identifier, "Expected method name"); + method->name = nameTok.value; + method->line = nameTok.line; + method->column = nameTok.column; - (void)expect(TokenType::LParen, "Expected '(' after 'constructor'"); - ctor->params = parseParameterList(); - (void)expect(TokenType::RParen, "Expected ')' after constructor parameters"); - (void)expect(TokenType::Arrow, "Expected '->' before constructor return type"); - std::unique_ptr retType = parseType(); + (void)expect(TokenType::LParen, "Expected '(' after method name"); + method->params = parseParameterList(); + (void)expect(TokenType::RParen, "Expected ')' after parameters"); - bool matches = false; - if (auto named = dynamic_cast(retType.get())) { - if (!named->nameParts.empty() && named->nameParts.back() == className) { - matches = true; - } - } - if (!matches) { - reportError("Constructor must return '" + className + "'"); - } + (void)expect(TokenType::Arrow, "Expected '->' before return type"); + method->returnType = parseType(); - if (match(TokenType::Equals)) { - const Token& defTok = expect(TokenType::Default, "Expected 'default' after '='"); - if (defTok.value != "default") { - reportError("Only '= default' is supported for constructors"); - } - (void)expect(TokenType::Semicolon, "Expected ';' after default constructor"); - ctor->isDefault = true; - ctor->body = nullptr; - } else { - ctor->body = parseBlock(); + if (check(TokenType::LBrace)) { + method->body = parseBlock(); + } else { + if (!method->isVirtual) { + reportError("Method must have a body unless it is marked 'virtual'"); } - return ctor; + (void)expect(TokenType::Semicolon, + "Expected ';' after virtual method declaration without a body"); + method->body = nullptr; } - std::unique_ptr Parser::parseDestructorDeclaration(Visibility vis) { - std::unique_ptr dtor = std::make_unique(); - dtor->visibility = vis; - const Token& dtorTok = previous(); - dtor->line = dtorTok.line; - dtor->column = dtorTok.column; + return method; +} - (void)expect(TokenType::LParen, "Expected '(' after 'destructor'"); - if (!check(TokenType::RParen)) { - reportError("Destructor cannot have parameters"); - } - (void)expect(TokenType::RParen, "Expected ')' after 'destructor'"); +std::unique_ptr Parser::parseConstructorDeclaration( + Visibility vis, const std::string& className) { + std::unique_ptr ctor = std::make_unique(); + ctor->visibility = vis; + const Token& ctorTok = previous(); + ctor->line = ctorTok.line; + ctor->column = ctorTok.column; - (void)expect(TokenType::Arrow, "Expected '->' before destructor return type"); - std::unique_ptr retType = parseType(); - if (!dynamic_cast(retType.get())) { - reportError("Destructor must return 'void'"); - } + (void)expect(TokenType::LParen, "Expected '(' after 'constructor'"); + ctor->params = parseParameterList(); + (void)expect(TokenType::RParen, "Expected ')' after constructor parameters"); + (void)expect(TokenType::Arrow, "Expected '->' before constructor return type"); + std::unique_ptr retType = parseType(); - if (match(TokenType::Equals)) { - const Token& defTok = expect(TokenType::Default, "Expected 'default' after '='"); - if (defTok.value != "default") { - reportError("Only '= default' is supported for destructors"); - } - (void)expect(TokenType::Semicolon, "Expected ';' after default destructor"); - dtor->isDefault = true; - dtor->body = nullptr; - } else { - dtor->body = parseBlock(); + bool matches = false; + if (auto named = dynamic_cast(retType.get())) { + if (!named->nameParts.empty() && named->nameParts.back() == className) { + matches = true; } - return dtor; } - - // Declarations - std::unique_ptr Parser::parseVariableDeclaration(bool isFinal, - bool allowMultiple) { - return parseVariableDeclaration(nullptr, isFinal, allowMultiple); + if (!matches) { + reportError("Constructor must return '" + className + "'"); } - std::unique_ptr Parser::parseVariableDeclaration( - std::unique_ptr preParsedType, bool isFinal, bool allowMultiple) { - std::unique_ptr var = std::make_unique(); - var->isFinal = isFinal; - - // Annotations - var->annotations = parseAnnotations(); - for (auto& ann : var->annotations) { - if (ann->name == "tracked") - var->isTracked = true; - } - - if (preParsedType) { - var->varType = std::move(preParsedType); - } else { - var->varType = parseType(); - } - - // Name - if (!check(TokenType::Identifier)) { - reportError("Expected variable name"); + if (match(TokenType::Equals)) { + const Token& defTok = expect(TokenType::Default, "Expected 'default' after '='"); + if (defTok.value != "default") { + reportError("Only '= default' is supported for constructors"); } - const Token& variableToken = advance(); - var->name = variableToken.value; - var->line = variableToken.line; - var->column = variableToken.column; - - // Initializer - if (match(TokenType::Equals)) { - var->initializer = parseExpression(); - } - - bool isQubitType = false; - if (auto prim = dynamic_cast(var->varType.get())) - isQubitType = prim->name == "qubit"; - - bool hasInitializer = var->initializer != nullptr; - // Support comma-separated qubit declarations (qubit a, b, c;). - while (match(TokenType::Comma)) { - if (!allowMultiple) - reportError("Multiple declarations not allowed in this context"); - if (!isQubitType) - reportError("only 'qubit' may be multi-declared"); - if (hasInitializer) - reportError("Cannot initialise multiple qubit declarations"); - const Token& extraToken = - expect(TokenType::Identifier, "Expected variable name after ','"); - std::unique_ptr extraVar = std::make_unique(); - extraVar->isFinal = isFinal; - extraVar->annotations = cloneAnnotations(var->annotations); - extraVar->varType = cloneType(*var->varType); - extraVar->name = extraToken.value; - extraVar->line = extraToken.line; - extraVar->column = extraToken.column; - m_extraStatements.push_back(std::move(extraVar)); - } - - (void)expect(TokenType::Semicolon, "expected ';' after declaration"); - - return var; + (void)expect(TokenType::Semicolon, "Expected ';' after default constructor"); + ctor->isDefault = true; + ctor->body = nullptr; + } else { + ctor->body = parseBlock(); } - - // @tracked - std::unique_ptr Parser::parseVariableAnnotation() { - (void)expect(TokenType::At, "Expected '@' to begin annotation"); - - if (!check(TokenType::Tracked)) { - const Token& invalid = peek(); - std::string invalidName = invalid.value.empty() ? std::string("") : invalid.value; - reportError(std::string("\"") + "@" + invalidName + - "\" is not a valid Bloch variable annotation"); - } - Token annotationToken = advance(); - std::unique_ptr annotation = std::make_unique(); - annotation->name = annotationToken.value; - annotation->isVariableAnnotation = true; - return annotation; + return ctor; +} + +std::unique_ptr Parser::parseDestructorDeclaration(Visibility vis) { + std::unique_ptr dtor = std::make_unique(); + dtor->visibility = vis; + const Token& dtorTok = previous(); + dtor->line = dtorTok.line; + dtor->column = dtorTok.column; + + (void)expect(TokenType::LParen, "Expected '(' after 'destructor'"); + if (!check(TokenType::RParen)) { + reportError("Destructor cannot have parameters"); } + (void)expect(TokenType::RParen, "Expected ')' after 'destructor'"); - //@quantum, @shots(N) - std::unique_ptr Parser::parseFunctionAnnotation() { - (void)expect(TokenType::At, "Expected '@' to begin annotation"); - - if (!check(TokenType::Quantum) && !check(TokenType::Shots)) { - const Token& invalid = peek(); - std::string invalidName = invalid.value.empty() ? std::string("") : invalid.value; - reportError(std::string("\"") + "@" + invalidName + - "\" is not a valid Bloch function/method annotation"); - } - Token annotationToken = advance(); - Token numberOfShots; - if (annotationToken.type == TokenType::Shots) { - (void)expect(TokenType::LParen, "Expected opening bracket '('"); - numberOfShots = expect(TokenType::IntegerLiteral, "Number of shots must be an integer"); - (void)expect(TokenType::RParen, "Expected closing bracket ')'"); - } - std::unique_ptr annotation = std::make_unique(); - annotation->name = annotationToken.value; - annotation->value = numberOfShots.value.empty() ? std::string{""} : numberOfShots.value; - annotation->isFunctionAnnotation = true; - return annotation; + (void)expect(TokenType::Arrow, "Expected '->' before destructor return type"); + std::unique_ptr retType = parseType(); + if (!dynamic_cast(retType.get())) { + reportError("Destructor must return 'void'"); } - std::vector> Parser::parseAnnotations() { - std::vector> annotations; - - while (check(TokenType::At)) { - if (checkNext(TokenType::Tracked)) { - annotations.push_back(parseVariableAnnotation()); - } else if (checkNext(TokenType::Quantum) || checkNext(TokenType::Shots)) { - annotations.push_back(parseFunctionAnnotation()); - } else { - const Token& invalid = - m_current + 1 < m_tokens.size() ? m_tokens[m_current + 1] : peek(); - const std::string invalidName = - invalid.value.empty() ? std::string{} : invalid.value; - reportError(std::string("\"") + "@" + invalidName + - "\" is not a valid Bloch annotation"); - } + if (match(TokenType::Equals)) { + const Token& defTok = expect(TokenType::Default, "Expected 'default' after '='"); + if (defTok.value != "default") { + reportError("Only '= default' is supported for destructors"); } + (void)expect(TokenType::Semicolon, "Expected ';' after default destructor"); + dtor->isDefault = true; + dtor->body = nullptr; + } else { + dtor->body = parseBlock(); + } + return dtor; +} + +// Declarations +std::unique_ptr Parser::parseVariableDeclaration(bool isFinal, + bool allowMultiple) { + return parseVariableDeclaration(nullptr, isFinal, allowMultiple); +} + +std::unique_ptr Parser::parseVariableDeclaration( + std::unique_ptr preParsedType, bool isFinal, bool allowMultiple) { + std::unique_ptr var = std::make_unique(); + var->isFinal = isFinal; + + // Annotations + var->annotations = parseAnnotations(); + for (auto& ann : var->annotations) { + if (ann->name == "tracked") + var->isTracked = true; + } - return annotations; + if (preParsedType) { + var->varType = std::move(preParsedType); + } else { + var->varType = parseType(); } - // Statements - std::unique_ptr Parser::parseStatement() { - if (check(TokenType::LBrace)) - return parseBlock(); + // Name + if (!check(TokenType::Identifier)) { + reportError("Expected variable name"); + } + const Token& variableToken = advance(); + var->name = variableToken.value; + var->line = variableToken.line; + var->column = variableToken.column; + + // Initializer + if (match(TokenType::Equals)) { + var->initializer = parseExpression(); + } - bool isFinal = match(TokenType::Final); - bool typeAhead = isTypeAhead(); + bool isQubitType = false; + if (auto prim = dynamic_cast(var->varType.get())) + isQubitType = prim->name == "qubit"; + + bool hasInitializer = var->initializer != nullptr; + // Support comma-separated qubit declarations (qubit a, b, c;). + while (match(TokenType::Comma)) { + if (!allowMultiple) + reportError("Multiple declarations not allowed in this context"); + if (!isQubitType) + reportError("only 'qubit' may be multi-declared"); + if (hasInitializer) + reportError("Cannot initialise multiple qubit declarations"); + const Token& extraToken = expect(TokenType::Identifier, "Expected variable name after ','"); + std::unique_ptr extraVar = std::make_unique(); + extraVar->isFinal = isFinal; + extraVar->annotations = cloneAnnotations(var->annotations); + extraVar->varType = cloneType(*var->varType); + extraVar->name = extraToken.value; + extraVar->line = extraToken.line; + extraVar->column = extraToken.column; + m_extraStatements.push_back(std::move(extraVar)); + } - // Match primitive declarations or annotated declarations - if (check(TokenType::At) || typeAhead) { - if (isFinal && !typeAhead && !check(TokenType::At)) { - reportError("Expected variable type after 'final'"); - } - return parseVariableDeclaration(isFinal); - } + (void)expect(TokenType::Semicolon, "expected ';' after declaration"); - // Standard statements - if (match(TokenType::Return)) - return parseReturn(); - if (match(TokenType::If)) - return parseIf(); - if (match(TokenType::For)) - return parseFor(); - if (match(TokenType::While)) - return parseWhile(); - if (match(TokenType::Echo)) - return parseEcho(); - if (match(TokenType::Reset)) - return parseReset(); - if (match(TokenType::Measure)) - return parseMeasure(); - if (match(TokenType::Destroy)) - return parseDestroy(); - - if (check(TokenType::Identifier) && checkNext(TokenType::Equals)) - return parseAssignment(); + return var; +} - std::unique_ptr expr = parseExpression(); - if (match(TokenType::Question)) { - std::unique_ptr thenBranch = parseStatement(); - (void)expect(TokenType::Colon, "Expected ':' after true branch"); - std::unique_ptr elseBranch = parseStatement(); - std::unique_ptr stmt = std::make_unique(); - stmt->condition = std::move(expr); - stmt->thenBranch = std::move(thenBranch); - stmt->elseBranch = std::move(elseBranch); - return stmt; - } +// @tracked +std::unique_ptr Parser::parseVariableAnnotation() { + (void)expect(TokenType::At, "Expected '@' to begin annotation"); - (void)expect(TokenType::Semicolon, "Expected ';' after expression"); - std::unique_ptr stmt = std::make_unique(); - stmt->expression = std::move(expr); - return stmt; + if (!check(TokenType::Tracked)) { + const Token& invalid = peek(); + std::string invalidName = invalid.value.empty() ? std::string("") : invalid.value; + reportError(std::string("\"") + "@" + invalidName + + "\" is not a valid Bloch variable annotation"); } - - // {...} - std::unique_ptr Parser::parseBlock() { - const Token& lbrace = expect(TokenType::LBrace, "Expected '{' to start block"); - - std::unique_ptr block = std::make_unique(); - block->line = lbrace.line; - block->column = lbrace.column; - while (!check(TokenType::RBrace) && !isAtEnd()) { - block->statements.push_back(parseStatement()); - flushExtraStatements(block->statements); - } - - (void)expect(TokenType::RBrace, "Expected '}' to end block"); - return block; + Token annotationToken = advance(); + std::unique_ptr annotation = std::make_unique(); + annotation->name = annotationToken.value; + annotation->isVariableAnnotation = true; + return annotation; +} + +//@quantum, @shots(N) +std::unique_ptr Parser::parseFunctionAnnotation() { + (void)expect(TokenType::At, "Expected '@' to begin annotation"); + + if (!check(TokenType::Quantum) && !check(TokenType::Shots)) { + const Token& invalid = peek(); + std::string invalidName = invalid.value.empty() ? std::string("") : invalid.value; + reportError(std::string("\"") + "@" + invalidName + + "\" is not a valid Bloch function/method annotation"); } - - // return expr; - std::unique_ptr Parser::parseReturn() { - std::unique_ptr stmt = std::make_unique(); - stmt->line = previous().line; - stmt->column = previous().column; - - if (!check(TokenType::Semicolon)) { - stmt->value = parseExpression(); + Token annotationToken = advance(); + Token numberOfShots; + if (annotationToken.type == TokenType::Shots) { + (void)expect(TokenType::LParen, "Expected opening bracket '('"); + numberOfShots = expect(TokenType::IntegerLiteral, "Number of shots must be an integer"); + (void)expect(TokenType::RParen, "Expected closing bracket ')'"); + } + std::unique_ptr annotation = std::make_unique(); + annotation->name = annotationToken.value; + annotation->value = numberOfShots.value.empty() ? std::string{""} : numberOfShots.value; + annotation->isFunctionAnnotation = true; + return annotation; +} + +std::vector> Parser::parseAnnotations() { + std::vector> annotations; + + while (check(TokenType::At)) { + if (checkNext(TokenType::Tracked)) { + annotations.push_back(parseVariableAnnotation()); + } else if (checkNext(TokenType::Quantum) || checkNext(TokenType::Shots)) { + annotations.push_back(parseFunctionAnnotation()); + } else { + const Token& invalid = + m_current + 1 < m_tokens.size() ? m_tokens[m_current + 1] : peek(); + const std::string invalidName = invalid.value.empty() ? std::string{} : invalid.value; + reportError(std::string("\"") + "@" + invalidName + + "\" is not a valid Bloch annotation"); } - - (void)expect(TokenType::Semicolon, "Expected ';' after return value"); - return stmt; } - // if (cond) {...} else {...} - std::unique_ptr Parser::parseIf() { - (void)expect(TokenType::LParen, "Expected '(' after 'if'"); - std::unique_ptr condition = parseExpression(); - (void)expect(TokenType::RParen, "Expected ')' after condition"); + return annotations; +} - std::unique_ptr thenBranch = parseBlock(); +// Statements +std::unique_ptr Parser::parseStatement() { + if (check(TokenType::LBrace)) + return parseBlock(); - std::unique_ptr elseBranch = nullptr; - if (match(TokenType::Else)) { - elseBranch = parseBlock(); + bool isFinal = match(TokenType::Final); + bool typeAhead = isTypeAhead(); + + // Match primitive declarations or annotated declarations + if (check(TokenType::At) || typeAhead) { + if (isFinal && !typeAhead && !check(TokenType::At)) { + reportError("Expected variable type after 'final'"); } + return parseVariableDeclaration(isFinal); + } - std::unique_ptr stmt = std::make_unique(); - stmt->condition = std::move(condition); + // Standard statements + if (match(TokenType::Return)) + return parseReturn(); + if (match(TokenType::If)) + return parseIf(); + if (match(TokenType::For)) + return parseFor(); + if (match(TokenType::While)) + return parseWhile(); + if (match(TokenType::Echo)) + return parseEcho(); + if (match(TokenType::Reset)) + return parseReset(); + if (match(TokenType::Measure)) + return parseMeasure(); + if (match(TokenType::Destroy)) + return parseDestroy(); + + if (check(TokenType::Identifier) && checkNext(TokenType::Equals)) + return parseAssignment(); + + std::unique_ptr expr = parseExpression(); + if (match(TokenType::Question)) { + std::unique_ptr thenBranch = parseStatement(); + (void)expect(TokenType::Colon, "Expected ':' after true branch"); + std::unique_ptr elseBranch = parseStatement(); + std::unique_ptr stmt = std::make_unique(); + stmt->condition = std::move(expr); stmt->thenBranch = std::move(thenBranch); stmt->elseBranch = std::move(elseBranch); return stmt; } - // for (init; cond; update) {...} - std::unique_ptr Parser::parseFor() { - (void)expect(TokenType::LParen, "Expected '(' after 'for'"); + (void)expect(TokenType::Semicolon, "Expected ';' after expression"); + std::unique_ptr stmt = std::make_unique(); + stmt->expression = std::move(expr); + return stmt; +} + +// {...} +std::unique_ptr Parser::parseBlock() { + const Token& lbrace = expect(TokenType::LBrace, "Expected '{' to start block"); + + std::unique_ptr block = std::make_unique(); + block->line = lbrace.line; + block->column = lbrace.column; + while (!check(TokenType::RBrace) && !isAtEnd()) { + block->statements.push_back(parseStatement()); + flushExtraStatements(block->statements); + } - std::unique_ptr initializer = nullptr; + (void)expect(TokenType::RBrace, "Expected '}' to end block"); + return block; +} - if (!check(TokenType::Semicolon)) { - bool isFinal = match(TokenType::Final); +// return expr; +std::unique_ptr Parser::parseReturn() { + std::unique_ptr stmt = std::make_unique(); + stmt->line = previous().line; + stmt->column = previous().column; - if (check(TokenType::Int) || check(TokenType::Float) || check(TokenType::Char) || - check(TokenType::String) || check(TokenType::Bit) || check(TokenType::Qubit)) { - initializer = parseVariableDeclaration(isFinal, false); - } else { - if (isFinal) { - reportError("Expected variable type after 'final'"); - } - initializer = parseExpressionStatement(); - } - } else { - (void)advance(); - } - - std::unique_ptr condition = parseExpression(); - (void)expect(TokenType::Semicolon, "Expected ';' after loop condition"); + if (!check(TokenType::Semicolon)) { + stmt->value = parseExpression(); + } - std::unique_ptr increment = parseExpression(); - (void)expect(TokenType::RParen, "Expected ')' after for clause"); + (void)expect(TokenType::Semicolon, "Expected ';' after return value"); + return stmt; +} - std::unique_ptr body = parseBlock(); +// if (cond) {...} else {...} +std::unique_ptr Parser::parseIf() { + (void)expect(TokenType::LParen, "Expected '(' after 'if'"); + std::unique_ptr condition = parseExpression(); + (void)expect(TokenType::RParen, "Expected ')' after condition"); - std::unique_ptr stmt = std::make_unique(); - stmt->initializer = std::move(initializer); - stmt->condition = std::move(condition); - stmt->increment = std::move(increment); - stmt->body = std::move(body); + std::unique_ptr thenBranch = parseBlock(); - return stmt; + std::unique_ptr elseBranch = nullptr; + if (match(TokenType::Else)) { + elseBranch = parseBlock(); } - // while (cond) {...} - std::unique_ptr Parser::parseWhile() { - (void)expect(TokenType::LParen, "Expected '(' after 'while'"); - std::unique_ptr condition = parseExpression(); - (void)expect(TokenType::RParen, "Expected ')' after condition"); - std::unique_ptr body = parseBlock(); - - std::unique_ptr stmt = std::make_unique(); - stmt->condition = std::move(condition); - stmt->body = std::move(body); - return stmt; - } + std::unique_ptr stmt = std::make_unique(); + stmt->condition = std::move(condition); + stmt->thenBranch = std::move(thenBranch); + stmt->elseBranch = std::move(elseBranch); + return stmt; +} - // echo(expr); - std::unique_ptr Parser::parseEcho() { - const Token& echoTok = previous(); - (void)expect(TokenType::LParen, "Expected '(' after 'echo'"); - std::unique_ptr value = parseExpression(); - (void)expect(TokenType::RParen, "Expected ')' after echo argument"); - (void)expect(TokenType::Semicolon, "Expected ';' after echo statement"); +// for (init; cond; update) {...} +std::unique_ptr Parser::parseFor() { + (void)expect(TokenType::LParen, "Expected '(' after 'for'"); - std::unique_ptr stmt = std::make_unique(); - stmt->value = std::move(value); - stmt->line = echoTok.line; - stmt->column = echoTok.column; - return stmt; - } + std::unique_ptr initializer = nullptr; - // reset q0; - std::unique_ptr Parser::parseReset() { - const Token& resetTok = previous(); - std::unique_ptr stmt = std::make_unique(); - stmt->target = parseExpression(); - (void)expect(TokenType::Semicolon, "Expected ';' after reset target"); - stmt->line = resetTok.line; - stmt->column = resetTok.column; - return stmt; - } + if (!check(TokenType::Semicolon)) { + bool isFinal = match(TokenType::Final); - // measure q0; - std::unique_ptr Parser::parseMeasure() { - const Token& measureTok = previous(); - std::unique_ptr stmt = std::make_unique(); - stmt->qubit = parseExpression(); - (void)expect(TokenType::Semicolon, "Expected ';' after measure target"); - stmt->line = measureTok.line; - stmt->column = measureTok.column; - return stmt; + if (check(TokenType::Int) || check(TokenType::Float) || check(TokenType::Char) || + check(TokenType::String) || check(TokenType::Bit) || check(TokenType::Qubit)) { + initializer = parseVariableDeclaration(isFinal, false); + } else { + if (isFinal) { + reportError("Expected variable type after 'final'"); + } + initializer = parseExpressionStatement(); + } + } else { + (void)advance(); } - // destroy expr; - std::unique_ptr Parser::parseDestroy() { - const Token& destroyTok = previous(); - std::unique_ptr stmt = std::make_unique(); - stmt->target = parseExpression(); - (void)expect(TokenType::Semicolon, "Expected ';' after destroy target"); - stmt->line = destroyTok.line; - stmt->column = destroyTok.column; - return stmt; + std::unique_ptr condition = parseExpression(); + (void)expect(TokenType::Semicolon, "Expected ';' after loop condition"); + + std::unique_ptr increment = parseExpression(); + (void)expect(TokenType::RParen, "Expected ')' after for clause"); + + std::unique_ptr body = parseBlock(); + + std::unique_ptr stmt = std::make_unique(); + stmt->initializer = std::move(initializer); + stmt->condition = std::move(condition); + stmt->increment = std::move(increment); + stmt->body = std::move(body); + + return stmt; +} + +// while (cond) {...} +std::unique_ptr Parser::parseWhile() { + (void)expect(TokenType::LParen, "Expected '(' after 'while'"); + std::unique_ptr condition = parseExpression(); + (void)expect(TokenType::RParen, "Expected ')' after condition"); + std::unique_ptr body = parseBlock(); + + std::unique_ptr stmt = std::make_unique(); + stmt->condition = std::move(condition); + stmt->body = std::move(body); + return stmt; +} + +// echo(expr); +std::unique_ptr Parser::parseEcho() { + const Token& echoTok = previous(); + (void)expect(TokenType::LParen, "Expected '(' after 'echo'"); + std::unique_ptr value = parseExpression(); + (void)expect(TokenType::RParen, "Expected ')' after echo argument"); + (void)expect(TokenType::Semicolon, "Expected ';' after echo statement"); + + std::unique_ptr stmt = std::make_unique(); + stmt->value = std::move(value); + stmt->line = echoTok.line; + stmt->column = echoTok.column; + return stmt; +} + +// reset q0; +std::unique_ptr Parser::parseReset() { + const Token& resetTok = previous(); + std::unique_ptr stmt = std::make_unique(); + stmt->target = parseExpression(); + (void)expect(TokenType::Semicolon, "Expected ';' after reset target"); + stmt->line = resetTok.line; + stmt->column = resetTok.column; + return stmt; +} + +// measure q0; +std::unique_ptr Parser::parseMeasure() { + const Token& measureTok = previous(); + std::unique_ptr stmt = std::make_unique(); + stmt->qubit = parseExpression(); + (void)expect(TokenType::Semicolon, "Expected ';' after measure target"); + stmt->line = measureTok.line; + stmt->column = measureTok.column; + return stmt; +} + +// destroy expr; +std::unique_ptr Parser::parseDestroy() { + const Token& destroyTok = previous(); + std::unique_ptr stmt = std::make_unique(); + stmt->target = parseExpression(); + (void)expect(TokenType::Semicolon, "Expected ';' after destroy target"); + stmt->line = destroyTok.line; + stmt->column = destroyTok.column; + return stmt; +} + +// x = expr; +std::unique_ptr Parser::parseAssignment() { + if (!check(TokenType::Identifier)) { + reportError("Expected variable name in assignment"); } - // x = expr; - std::unique_ptr Parser::parseAssignment() { - if (!check(TokenType::Identifier)) { - reportError("Expected variable name in assignment"); - } - - const Token& nameToken = advance(); - std::string name = nameToken.value; - (void)expect(TokenType::Equals, "Expected '=' in assignment"); - - std::unique_ptr stmt = std::make_unique(); - stmt->name = name; - stmt->line = nameToken.line; - stmt->column = nameToken.column; - stmt->value = parseExpression(); - - (void)expect(TokenType::Semicolon, "Expected ';' after assignment"); - return stmt; + const Token& nameToken = advance(); + std::string name = nameToken.value; + (void)expect(TokenType::Equals, "Expected '=' in assignment"); + + std::unique_ptr stmt = std::make_unique(); + stmt->name = name; + stmt->line = nameToken.line; + stmt->column = nameToken.column; + stmt->value = parseExpression(); + + (void)expect(TokenType::Semicolon, "Expected ';' after assignment"); + return stmt; +} + +std::unique_ptr Parser::parseExpressionStatement() { + std::unique_ptr expr = parseExpression(); + (void)expect(TokenType::Semicolon, "Expected ';' after expression"); + std::unique_ptr stmt = std::make_unique(); + stmt->expression = std::move(expr); + return stmt; +} + +// Expressions (Pratt / precedence-table based) +std::unique_ptr Parser::parseExpression() { return parseAssignmentExpression(); } + +namespace { +/** + * Binding powers for Pratt parsing. + * lbp = left binding power, rbp = right binding power. + * For left-associative infix operators: lbp == rbp - 1. + * For postfix operators we reuse the table with Kind::Postfix. + * New operators are added by extending infixBinding() below. + */ +struct Binding { + int lbp; + int rbp; + enum class Kind { Infix, Postfix } kind = Kind::Infix; +}; + +// Returns binding power for an operator if it is handled in the Pratt loop. +std::optional infixBinding(TokenType type) { + switch (type) { + case TokenType::PipePipe: + return Binding{3, 4, Binding::Kind::Infix}; // logical or (left) + case TokenType::AmpersandAmpersand: + return Binding{4, 5, Binding::Kind::Infix}; // logical and (left) + case TokenType::Pipe: + return Binding{5, 6, Binding::Kind::Infix}; // bitwise or (left) + case TokenType::Caret: + return Binding{6, 7, Binding::Kind::Infix}; // bitwise xor (left) + case TokenType::Ampersand: + return Binding{7, 8, Binding::Kind::Infix}; // bitwise and (left) + case TokenType::EqualEqual: + case TokenType::BangEqual: + return Binding{8, 9, Binding::Kind::Infix}; // equality (left) + case TokenType::Greater: + case TokenType::Less: + case TokenType::GreaterEqual: + case TokenType::LessEqual: + return Binding{9, 10, Binding::Kind::Infix}; // relational (left) + case TokenType::Plus: + case TokenType::Minus: + return Binding{11, 12, Binding::Kind::Infix}; // additive (left) + case TokenType::Star: + case TokenType::Slash: + case TokenType::Percent: + return Binding{12, 13, Binding::Kind::Infix}; // multiplicative (left) + case TokenType::Dot: + case TokenType::LParen: // call + case TokenType::LBracket: // index + case TokenType::PlusPlus: // postfix + case TokenType::MinusMinus: + return Binding{16, 17, Binding::Kind::Postfix}; // postfix/call/member + default: + return std::nullopt; } - - std::unique_ptr Parser::parseExpressionStatement() { - std::unique_ptr expr = parseExpression(); - (void)expect(TokenType::Semicolon, "Expected ';' after expression"); - std::unique_ptr stmt = std::make_unique(); - stmt->expression = std::move(expr); - return stmt; +} + +constexpr int kPrefixBindingPower = 14; // binds tighter than binary ops, looser than postfix +} // namespace + +std::unique_ptr Parser::parseAssignmentExpression() { + // Right-associative assignment built on top of Pratt for the rest. + std::unique_ptr left = parsePrattExpression(0); + + if (match(TokenType::Equals)) { + std::unique_ptr value = parseAssignmentExpression(); + + if (auto varExpr = dynamic_cast(left.get())) { + int line = varExpr->line; + int column = varExpr->column; + std::string name = varExpr->name; + std::unique_ptr assign = + std::make_unique(name, std::move(value)); + assign->line = line; + assign->column = column; + return assign; + } else if (dynamic_cast(left.get())) { + std::unique_ptr idx(static_cast(left.release())); + int line = idx->line; + int column = idx->column; + std::unique_ptr arrayAssign = + std::make_unique( + std::move(idx->collection), std::move(idx->index), std::move(value)); + arrayAssign->line = line; + arrayAssign->column = column; + return arrayAssign; + } else if (dynamic_cast(left.get())) { + std::unique_ptr mem( + static_cast(left.release())); + int line = mem->line; + int column = mem->column; + std::unique_ptr memberAssign = + std::make_unique(std::move(mem->object), mem->member, + std::move(value)); + memberAssign->line = line; + memberAssign->column = column; + return memberAssign; + } + + reportError("Invalid assignment target"); } - // Expressions (Pratt / precedence-table based) - std::unique_ptr Parser::parseExpression() { return parseAssignmentExpression(); } - - namespace { - /** - * Binding powers for Pratt parsing. - * lbp = left binding power, rbp = right binding power. - * For left-associative infix operators: lbp == rbp - 1. - * For postfix operators we reuse the table with Kind::Postfix. - * New operators are added by extending infixBinding() below. - */ - struct Binding { - int lbp; - int rbp; - enum class Kind { Infix, Postfix } kind = Kind::Infix; - }; - - // Returns binding power for an operator if it is handled in the Pratt loop. - std::optional infixBinding(TokenType type) { - switch (type) { - case TokenType::PipePipe: - return Binding{3, 4, Binding::Kind::Infix}; // logical or (left) - case TokenType::AmpersandAmpersand: - return Binding{4, 5, Binding::Kind::Infix}; // logical and (left) - case TokenType::Pipe: - return Binding{5, 6, Binding::Kind::Infix}; // bitwise or (left) - case TokenType::Caret: - return Binding{6, 7, Binding::Kind::Infix}; // bitwise xor (left) - case TokenType::Ampersand: - return Binding{7, 8, Binding::Kind::Infix}; // bitwise and (left) - case TokenType::EqualEqual: - case TokenType::BangEqual: - return Binding{8, 9, Binding::Kind::Infix}; // equality (left) - case TokenType::Greater: - case TokenType::Less: - case TokenType::GreaterEqual: - case TokenType::LessEqual: - return Binding{9, 10, Binding::Kind::Infix}; // relational (left) - case TokenType::Plus: - case TokenType::Minus: - return Binding{11, 12, Binding::Kind::Infix}; // additive (left) - case TokenType::Star: - case TokenType::Slash: - case TokenType::Percent: - return Binding{12, 13, Binding::Kind::Infix}; // multiplicative (left) - case TokenType::Dot: - case TokenType::LParen: // call - case TokenType::LBracket: // index - case TokenType::PlusPlus: // postfix - case TokenType::MinusMinus: - return Binding{16, 17, Binding::Kind::Postfix}; // postfix/call/member - default: - return std::nullopt; - } - } - - constexpr int kPrefixBindingPower = - 14; // binds tighter than binary ops, looser than postfix - } // namespace - - std::unique_ptr Parser::parseAssignmentExpression() { - // Right-associative assignment built on top of Pratt for the rest. - std::unique_ptr left = parsePrattExpression(0); - - if (match(TokenType::Equals)) { - std::unique_ptr value = parseAssignmentExpression(); - - if (auto varExpr = dynamic_cast(left.get())) { - int line = varExpr->line; - int column = varExpr->column; - std::string name = varExpr->name; - std::unique_ptr assign = - std::make_unique(name, std::move(value)); - assign->line = line; - assign->column = column; - return assign; - } else if (dynamic_cast(left.get())) { - std::unique_ptr idx(static_cast(left.release())); - int line = idx->line; - int column = idx->column; - std::unique_ptr arrayAssign = - std::make_unique( - std::move(idx->collection), std::move(idx->index), std::move(value)); - arrayAssign->line = line; - arrayAssign->column = column; - return arrayAssign; - } else if (dynamic_cast(left.get())) { - std::unique_ptr mem( - static_cast(left.release())); - int line = mem->line; - int column = mem->column; - std::unique_ptr memberAssign = - std::make_unique(std::move(mem->object), - mem->member, std::move(value)); - memberAssign->line = line; - memberAssign->column = column; - return memberAssign; - } - - reportError("Invalid assignment target"); - } + return left; +} - return left; - } +std::unique_ptr Parser::parsePrattExpression(int minBp) { + std::unique_ptr left = parsePrefixExpression(); - std::unique_ptr Parser::parsePrattExpression(int minBp) { - std::unique_ptr left = parsePrefixExpression(); + while (true) { + const Token& tok = peek(); + auto binding = infixBinding(tok.type); + if (!binding || binding->lbp < minBp) + break; - while (true) { - const Token& tok = peek(); - auto binding = infixBinding(tok.type); - if (!binding || binding->lbp < minBp) - break; + (void)advance(); // consume operator / postfix marker - (void)advance(); // consume operator / postfix marker - - if (binding->kind == Binding::Kind::Postfix) { - switch (tok.type) { - case TokenType::LParen: { - const Token& lparen = tok; - std::vector> args; - if (!check(TokenType::RParen)) { - do { - args.push_back(parseExpression()); - } while (match(TokenType::Comma)); - } - (void)expect(TokenType::RParen, "Expected ')' after arguments"); - int calleeLine = left ? left->line : lparen.line; - int calleeColumn = left ? left->column : lparen.column; - std::unique_ptr call = - std::make_unique(std::move(left), std::move(args)); - call->line = calleeLine; - call->column = calleeColumn; - left = std::move(call); - continue; + if (binding->kind == Binding::Kind::Postfix) { + switch (tok.type) { + case TokenType::LParen: { + const Token& lparen = tok; + std::vector> args; + if (!check(TokenType::RParen)) { + do { + args.push_back(parseExpression()); + } while (match(TokenType::Comma)); } - case TokenType::LBracket: { - const Token& lbr = tok; - std::unique_ptr idxExpr = - std::make_unique(); - idxExpr->collection = std::move(left); - std::unique_ptr indexNode = parseExpression(); - - // Constant negative index guard preserved from legacy parser. - bool negativeConst = false; - if (auto lit = dynamic_cast(indexNode.get())) { - if (lit->literalType == "int") { - try { - int v = std::stoi(lit->value); - negativeConst = v < 0; - } catch (...) { - } + (void)expect(TokenType::RParen, "Expected ')' after arguments"); + int calleeLine = left ? left->line : lparen.line; + int calleeColumn = left ? left->column : lparen.column; + std::unique_ptr call = + std::make_unique(std::move(left), std::move(args)); + call->line = calleeLine; + call->column = calleeColumn; + left = std::move(call); + continue; + } + case TokenType::LBracket: { + const Token& lbr = tok; + std::unique_ptr idxExpr = std::make_unique(); + idxExpr->collection = std::move(left); + std::unique_ptr indexNode = parseExpression(); + + // Constant negative index guard preserved from legacy parser. + bool negativeConst = false; + if (auto lit = dynamic_cast(indexNode.get())) { + if (lit->literalType == "int") { + try { + int v = std::stoi(lit->value); + negativeConst = v < 0; + } catch (...) { } - } else if (auto unary = dynamic_cast(indexNode.get())) { - if (unary->op == "-") { - if (auto rlit = - dynamic_cast(unary->right.get())) { - if (rlit->literalType == "int") { - try { - int v = std::stoi(rlit->value); - negativeConst = v > 0; - } catch (...) { - } + } + } else if (auto unary = dynamic_cast(indexNode.get())) { + if (unary->op == "-") { + if (auto rlit = dynamic_cast(unary->right.get())) { + if (rlit->literalType == "int") { + try { + int v = std::stoi(rlit->value); + negativeConst = v > 0; + } catch (...) { } } } } - if (negativeConst) { - throw BlochError(ErrorCategory::Parse, lbr.line, lbr.column, - "array index must be non-negative"); - } - - idxExpr->index = std::move(indexNode); - (void)expect(TokenType::RBracket, "Expected ']' after index expression"); - idxExpr->line = lbr.line; - idxExpr->column = lbr.column; - left = std::move(idxExpr); - continue; } - case TokenType::Dot: { - const Token& dotTok = tok; - const Token& memberTok = - expect(TokenType::Identifier, "Expected member name after '.'"); - std::unique_ptr member = - std::make_unique(); - member->object = std::move(left); - member->member = memberTok.value; - member->line = dotTok.line; - member->column = dotTok.column; - left = std::move(member); - continue; + if (negativeConst) { + throw BlochError(ErrorCategory::Parse, lbr.line, lbr.column, + "array index must be non-negative"); } - case TokenType::PlusPlus: - case TokenType::MinusMinus: { - std::unique_ptr post = - std::make_unique(tok.value, std::move(left)); - post->line = tok.line; - post->column = tok.column; - left = std::move(post); - continue; - } - default: - break; + + idxExpr->index = std::move(indexNode); + (void)expect(TokenType::RBracket, "Expected ']' after index expression"); + idxExpr->line = lbr.line; + idxExpr->column = lbr.column; + left = std::move(idxExpr); + continue; + } + case TokenType::Dot: { + const Token& dotTok = tok; + const Token& memberTok = + expect(TokenType::Identifier, "Expected member name after '.'"); + std::unique_ptr member = + std::make_unique(); + member->object = std::move(left); + member->member = memberTok.value; + member->line = dotTok.line; + member->column = dotTok.column; + left = std::move(member); + continue; } + case TokenType::PlusPlus: + case TokenType::MinusMinus: { + std::unique_ptr post = + std::make_unique(tok.value, std::move(left)); + post->line = tok.line; + post->column = tok.column; + left = std::move(post); + continue; + } + default: + break; } - - // Infix binary - std::unique_ptr right = parsePrattExpression(binding->rbp); - std::unique_ptr bin = - std::make_unique(tok.value, std::move(left), std::move(right)); - bin->line = tok.line; - bin->column = tok.column; - left = std::move(bin); } - return left; + // Infix binary + std::unique_ptr right = parsePrattExpression(binding->rbp); + std::unique_ptr bin = + std::make_unique(tok.value, std::move(left), std::move(right)); + bin->line = tok.line; + bin->column = tok.column; + left = std::move(bin); } - std::unique_ptr Parser::parsePrefixExpression() { - const Token& tok = peek(); - if (tok.type == TokenType::Minus || tok.type == TokenType::Bang || - tok.type == TokenType::Tilde) { - (void)advance(); - std::unique_ptr right = parsePrattExpression(kPrefixBindingPower); - std::unique_ptr un = - std::make_unique(tok.value, std::move(right)); - un->line = tok.line; - un->column = tok.column; - return un; - } - - return parsePrimary(); + return left; +} + +std::unique_ptr Parser::parsePrefixExpression() { + const Token& tok = peek(); + if (tok.type == TokenType::Minus || tok.type == TokenType::Bang || + tok.type == TokenType::Tilde) { + (void)advance(); + std::unique_ptr right = parsePrattExpression(kPrefixBindingPower); + std::unique_ptr un = + std::make_unique(tok.value, std::move(right)); + un->line = tok.line; + un->column = tok.column; + return un; } - std::unique_ptr Parser::parseUnary() { return parsePrefixExpression(); } - - std::unique_ptr Parser::parsePrimary() { - if (match(TokenType::IntegerLiteral) || match(TokenType::LongLiteral) || - match(TokenType::FloatLiteral) || match(TokenType::BitLiteral) || - match(TokenType::StringLiteral) || match(TokenType::CharLiteral) || - match(TokenType::True) || match(TokenType::False)) { - Token tok = previous(); - std::string litType; - switch (tok.type) { - case TokenType::IntegerLiteral: - litType = "int"; - break; - case TokenType::LongLiteral: - litType = "long"; - break; - case TokenType::FloatLiteral: - litType = "float"; - break; - case TokenType::BitLiteral: - litType = "bit"; - break; - case TokenType::CharLiteral: - litType = "char"; - break; - case TokenType::True: - case TokenType::False: - litType = "boolean"; - break; - case TokenType::StringLiteral: - litType = "string"; - break; - default: - break; - } - return std::make_unique(LiteralExpression{tok.value, litType}); - } + return parsePrimary(); +} - if (match(TokenType::Null)) { - const Token& tok = previous(); - std::unique_ptr expr = std::make_unique(); - expr->line = tok.line; - expr->column = tok.column; - return expr; - } +std::unique_ptr Parser::parseUnary() { return parsePrefixExpression(); } - if (match(TokenType::Measure)) { - const Token& measureTok = previous(); - std::unique_ptr target = parseExpression(); - std::unique_ptr expr = - std::make_unique(MeasureExpression{std::move(target)}); - expr->line = measureTok.line; - expr->column = measureTok.column; - return expr; +std::unique_ptr Parser::parsePrimary() { + if (match(TokenType::IntegerLiteral) || match(TokenType::LongLiteral) || + match(TokenType::FloatLiteral) || match(TokenType::BitLiteral) || + match(TokenType::StringLiteral) || match(TokenType::CharLiteral) || + match(TokenType::True) || match(TokenType::False)) { + Token tok = previous(); + std::string litType; + switch (tok.type) { + case TokenType::IntegerLiteral: + litType = "int"; + break; + case TokenType::LongLiteral: + litType = "long"; + break; + case TokenType::FloatLiteral: + litType = "float"; + break; + case TokenType::BitLiteral: + litType = "bit"; + break; + case TokenType::CharLiteral: + litType = "char"; + break; + case TokenType::True: + case TokenType::False: + litType = "boolean"; + break; + case TokenType::StringLiteral: + litType = "string"; + break; + default: + break; } + return std::make_unique(LiteralExpression{tok.value, litType}); + } - if (match(TokenType::This)) { - const Token& tok = previous(); - std::unique_ptr expr = std::make_unique(); - expr->line = tok.line; - expr->column = tok.column; - return expr; - } + if (match(TokenType::Null)) { + const Token& tok = previous(); + std::unique_ptr expr = std::make_unique(); + expr->line = tok.line; + expr->column = tok.column; + return expr; + } - if (match(TokenType::Super)) { - const Token& tok = previous(); - std::unique_ptr expr = std::make_unique(); - expr->line = tok.line; - expr->column = tok.column; - return expr; - } + if (match(TokenType::Measure)) { + const Token& measureTok = previous(); + std::unique_ptr target = parseExpression(); + std::unique_ptr expr = + std::make_unique(MeasureExpression{std::move(target)}); + expr->line = measureTok.line; + expr->column = measureTok.column; + return expr; + } - if (match(TokenType::New)) { - const Token& newTok = previous(); - std::unique_ptr type = parseType(true); - (void)expect(TokenType::LParen, "Expected '(' after type in 'new' expression"); - std::vector> args = parseArgumentList(); - (void)expect(TokenType::RParen, "Expected ')' after arguments"); - std::unique_ptr expr = std::make_unique(); - expr->classType = std::move(type); - expr->arguments = std::move(args); - expr->line = newTok.line; - expr->column = newTok.column; - return expr; - } + if (match(TokenType::This)) { + const Token& tok = previous(); + std::unique_ptr expr = std::make_unique(); + expr->line = tok.line; + expr->column = tok.column; + return expr; + } - if (match(TokenType::Identifier)) { - const Token& token = previous(); - std::unique_ptr expr = - std::make_unique(VariableExpression{token.value}); - expr->line = token.line; - expr->column = token.column; - return expr; - } + if (match(TokenType::Super)) { + const Token& tok = previous(); + std::unique_ptr expr = std::make_unique(); + expr->line = tok.line; + expr->column = tok.column; + return expr; + } - if (match(TokenType::LBrace)) { - Token start = previous(); - std::unique_ptr expr = parseArrayLiteral(); - expr->line = start.line; - expr->column = start.column; - return expr; - } + if (match(TokenType::New)) { + const Token& newTok = previous(); + std::unique_ptr type = parseType(true); + (void)expect(TokenType::LParen, "Expected '(' after type in 'new' expression"); + std::vector> args = parseArgumentList(); + (void)expect(TokenType::RParen, "Expected ')' after arguments"); + std::unique_ptr expr = std::make_unique(); + expr->classType = std::move(type); + expr->arguments = std::move(args); + expr->line = newTok.line; + expr->column = newTok.column; + return expr; + } - if (match(TokenType::LParen)) { - const Token& lparen = previous(); - if (isTypeAhead()) { - std::unique_ptr targetType = parseType(); - (void)expect(TokenType::RParen, "Expected ')' after type in cast expression"); - std::unique_ptr operand = parseUnary(); - std::unique_ptr cast = - std::make_unique(std::move(targetType), std::move(operand)); - cast->line = lparen.line; - cast->column = lparen.column; - return cast; - } - std::unique_ptr expr = parseExpression(); - (void)expect(TokenType::RParen, "Expected ')' after expression"); - auto paren = - std::make_unique(ParenthesizedExpression{std::move(expr)}); - paren->line = lparen.line; - paren->column = lparen.column; - return paren; - } + if (match(TokenType::Identifier)) { + const Token& token = previous(); + std::unique_ptr expr = + std::make_unique(VariableExpression{token.value}); + expr->line = token.line; + expr->column = token.column; + return expr; + } - reportError("Expected expression"); - return nullptr; + if (match(TokenType::LBrace)) { + Token start = previous(); + std::unique_ptr expr = parseArrayLiteral(); + expr->line = start.line; + expr->column = start.column; + return expr; } - std::unique_ptr Parser::parseArrayLiteral() { - std::vector> elements; - if (!check(TokenType::RBrace)) { - do { - elements.push_back(parseExpression()); - } while (match(TokenType::Comma)); + if (match(TokenType::LParen)) { + const Token& lparen = previous(); + if (isTypeAhead()) { + std::unique_ptr targetType = parseType(); + (void)expect(TokenType::RParen, "Expected ')' after type in cast expression"); + std::unique_ptr operand = parseUnary(); + std::unique_ptr cast = + std::make_unique(std::move(targetType), std::move(operand)); + cast->line = lparen.line; + cast->column = lparen.column; + return cast; } - (void)expect(TokenType::RBrace, "Expected '}' after array literal"); - return std::make_unique(std::move(elements)); + std::unique_ptr expr = parseExpression(); + (void)expect(TokenType::RParen, "Expected ')' after expression"); + auto paren = + std::make_unique(ParenthesizedExpression{std::move(expr)}); + paren->line = lparen.line; + paren->column = lparen.column; + return paren; } - // Literals - std::unique_ptr Parser::parseLiteral() { - const Token& token = advance(); + reportError("Expected expression"); + return nullptr; +} - switch (token.type) { - case TokenType::IntegerLiteral: - return std::make_unique(LiteralExpression{token.value, "int"}); - case TokenType::LongLiteral: - return std::make_unique(LiteralExpression{token.value, "long"}); - case TokenType::FloatLiteral: - return std::make_unique(LiteralExpression{token.value, "float"}); - case TokenType::BitLiteral: - return std::make_unique(LiteralExpression{token.value, "bit"}); - case TokenType::CharLiteral: - return std::make_unique(LiteralExpression{token.value, "char"}); - case TokenType::StringLiteral: - return std::make_unique( - LiteralExpression{token.value, "string"}); - case TokenType::Null: { - auto expr = std::make_unique(); - expr->line = token.line; - expr->column = token.column; - return expr; - } - default: - reportError("Expected a literal value."); - return nullptr; - } +std::unique_ptr Parser::parseArrayLiteral() { + std::vector> elements; + if (!check(TokenType::RBrace)) { + do { + elements.push_back(parseExpression()); + } while (match(TokenType::Comma)); } - - // Types - - std::unique_ptr Parser::parseType(bool allowEmptyTypeArguments) { - std::unique_ptr baseType; - if (check(TokenType::Void)) { - (void)advance(); - baseType = std::make_unique(); - } else if (check(TokenType::Int) || check(TokenType::Long) || check(TokenType::Float) || - check(TokenType::Char) || check(TokenType::String) || check(TokenType::Bit) || - check(TokenType::Qubit) || check(TokenType::Boolean)) { - baseType = parsePrimitiveType(); - } else if (check(TokenType::Identifier)) { - std::vector parts = parseQualifiedName(); - auto named = std::make_unique(parts); - if (match(TokenType::Less)) { - named->hasTypeArgumentList = true; - named->typeArguments = parseTypeArgumentList(allowEmptyTypeArguments); - } - baseType = std::move(named); - } else { - reportError("Expected type"); - return nullptr; + (void)expect(TokenType::RBrace, "Expected '}' after array literal"); + return std::make_unique(std::move(elements)); +} + +// Literals +std::unique_ptr Parser::parseLiteral() { + const Token& token = advance(); + + switch (token.type) { + case TokenType::IntegerLiteral: + return std::make_unique(LiteralExpression{token.value, "int"}); + case TokenType::LongLiteral: + return std::make_unique(LiteralExpression{token.value, "long"}); + case TokenType::FloatLiteral: + return std::make_unique(LiteralExpression{token.value, "float"}); + case TokenType::BitLiteral: + return std::make_unique(LiteralExpression{token.value, "bit"}); + case TokenType::CharLiteral: + return std::make_unique(LiteralExpression{token.value, "char"}); + case TokenType::StringLiteral: + return std::make_unique(LiteralExpression{token.value, "string"}); + case TokenType::Null: { + auto expr = std::make_unique(); + expr->line = token.line; + expr->column = token.column; + return expr; } + default: + reportError("Expected a literal value."); + return nullptr; + } +} + +// Types + +std::unique_ptr Parser::parseType(bool allowEmptyTypeArguments) { + std::unique_ptr baseType; + if (check(TokenType::Void)) { + (void)advance(); + baseType = std::make_unique(); + } else if (check(TokenType::Int) || check(TokenType::Long) || check(TokenType::Float) || + check(TokenType::Char) || check(TokenType::String) || check(TokenType::Bit) || + check(TokenType::Qubit) || check(TokenType::Boolean)) { + baseType = parsePrimitiveType(); + } else if (check(TokenType::Identifier)) { + std::vector parts = parseQualifiedName(); + auto named = std::make_unique(parts); + if (match(TokenType::Less)) { + named->hasTypeArgumentList = true; + named->typeArguments = parseTypeArgumentList(allowEmptyTypeArguments); + } + baseType = std::move(named); + } else { + reportError("Expected type"); + return nullptr; + } - while (match(TokenType::LBracket)) { - int arrSize = -1; - std::unique_ptr sizeExpr = nullptr; - if (!check(TokenType::RBracket)) { - if (check(TokenType::IntegerLiteral)) { - const Token& sizeTok = advance(); - try { - arrSize = std::stoi(sizeTok.value); - } catch (...) { - reportError("Invalid integer size in array type"); - } - } else { - sizeExpr = parseExpression(); + while (match(TokenType::LBracket)) { + int arrSize = -1; + std::unique_ptr sizeExpr = nullptr; + if (!check(TokenType::RBracket)) { + if (check(TokenType::IntegerLiteral)) { + const Token& sizeTok = advance(); + try { + arrSize = std::stoi(sizeTok.value); + } catch (...) { + reportError("Invalid integer size in array type"); } + } else { + sizeExpr = parseExpression(); } - (void)expect(TokenType::RBracket, "Expected ']' after '[' in array type"); - if (dynamic_cast(baseType.get())) { - reportError("array element type cannot be 'void'"); - } - baseType = parseArrayType(std::move(baseType), arrSize, std::move(sizeExpr)); } - - return baseType; + (void)expect(TokenType::RBracket, "Expected ']' after '[' in array type"); + if (dynamic_cast(baseType.get())) { + reportError("array element type cannot be 'void'"); + } + baseType = parseArrayType(std::move(baseType), arrSize, std::move(sizeExpr)); } - std::unique_ptr Parser::parsePrimitiveType() { - if (check(TokenType::Int) || check(TokenType::Long) || check(TokenType::Float) || - check(TokenType::Char) || check(TokenType::String) || check(TokenType::Bit) || - check(TokenType::Qubit) || check(TokenType::Boolean)) { - std::string typeName = advance().value; - return std::make_unique(typeName); - } + return baseType; +} - reportError("Expected primitive type"); - return nullptr; +std::unique_ptr Parser::parsePrimitiveType() { + if (check(TokenType::Int) || check(TokenType::Long) || check(TokenType::Float) || + check(TokenType::Char) || check(TokenType::String) || check(TokenType::Bit) || + check(TokenType::Qubit) || check(TokenType::Boolean)) { + std::string typeName = advance().value; + return std::make_unique(typeName); } - std::unique_ptr Parser::parseArrayType(std::unique_ptr elementType, int size, - std::unique_ptr sizeExpr) { - return std::make_unique(std::move(elementType), size, std::move(sizeExpr)); - } + reportError("Expected primitive type"); + return nullptr; +} - std::vector> Parser::parseTypeParameters() { - std::vector> params; - (void)expect(TokenType::Less, "Expected '<' to start type parameters"); - if (check(TokenType::Greater)) { - (void)advance(); - return params; - } - do { - const Token& nameTok = expect(TokenType::Identifier, "Expected type parameter name"); - auto param = std::make_unique(); - param->name = nameTok.value; - param->line = nameTok.line; - param->column = nameTok.column; - if (match(TokenType::Extends)) { - param->bound = parseType(); - } - params.push_back(std::move(param)); - } while (match(TokenType::Comma)); - (void)expect(TokenType::Greater, "Expected '>' to end type parameters"); +std::unique_ptr Parser::parseArrayType(std::unique_ptr elementType, int size, + std::unique_ptr sizeExpr) { + return std::make_unique(std::move(elementType), size, std::move(sizeExpr)); +} + +std::vector> Parser::parseTypeParameters() { + std::vector> params; + (void)expect(TokenType::Less, "Expected '<' to start type parameters"); + if (check(TokenType::Greater)) { + (void)advance(); return params; } + do { + const Token& nameTok = expect(TokenType::Identifier, "Expected type parameter name"); + auto param = std::make_unique(); + param->name = nameTok.value; + param->line = nameTok.line; + param->column = nameTok.column; + if (match(TokenType::Extends)) { + param->bound = parseType(); + } + params.push_back(std::move(param)); + } while (match(TokenType::Comma)); + (void)expect(TokenType::Greater, "Expected '>' to end type parameters"); + return params; +} - std::vector> Parser::parseTypeArgumentList(bool allowEmpty) { - std::vector> args; - if (check(TokenType::Greater)) { - if (!allowEmpty) { - reportError("Expected type argument before '>'"); - } - (void)advance(); - return args; +std::vector> Parser::parseTypeArgumentList(bool allowEmpty) { + std::vector> args; + if (check(TokenType::Greater)) { + if (!allowEmpty) { + reportError("Expected type argument before '>'"); } - do { - args.push_back(parseType()); - } while (match(TokenType::Comma)); - (void)expect(TokenType::Greater, "Expected '>' after type arguments"); + (void)advance(); return args; } + do { + args.push_back(parseType()); + } while (match(TokenType::Comma)); + (void)expect(TokenType::Greater, "Expected '>' after type arguments"); + return args; +} - // Parameters and Argments - std::vector> Parser::parseParameterList() { - std::vector> parameters; +// Parameters and Argments +std::vector> Parser::parseParameterList() { + std::vector> parameters; - while (!check(TokenType::RParen)) { - std::unique_ptr param = std::make_unique(); + while (!check(TokenType::RParen)) { + std::unique_ptr param = std::make_unique(); - // Parse type - param->type = parseType(); + // Parse type + param->type = parseType(); - // Parse name - if (!check(TokenType::Identifier)) { - reportError("Expected parameter name."); - } - const Token& paramTok = advance(); - param->name = paramTok.value; - param->line = paramTok.line; - param->column = paramTok.column; - - parameters.push_back(std::move(param)); - - if (!match(TokenType::Comma)) - break; + // Parse name + if (!check(TokenType::Identifier)) { + reportError("Expected parameter name."); } + const Token& paramTok = advance(); + param->name = paramTok.value; + param->line = paramTok.line; + param->column = paramTok.column; - return parameters; - } + parameters.push_back(std::move(param)); - std::vector> Parser::parseArgumentList() { - std::vector> args; + if (!match(TokenType::Comma)) + break; + } - if (check(TokenType::RParen)) { - return args; - } + return parameters; +} - do { - args.push_back(parseExpression()); - } while (match(TokenType::Comma)); +std::vector> Parser::parseArgumentList() { + std::vector> args; + if (check(TokenType::RParen)) { return args; } - std::unique_ptr Parser::cloneExpression(const Expression& expr) { - if (auto lit = dynamic_cast(&expr)) { - std::unique_ptr clone = - std::make_unique(lit->value, lit->literalType); - clone->line = lit->line; - clone->column = lit->column; - return clone; - } - if (auto nullLit = dynamic_cast(&expr)) { - std::unique_ptr clone = - std::make_unique(); - clone->line = nullLit->line; - clone->column = nullLit->column; - return clone; - } - if (auto var = dynamic_cast(&expr)) { - std::unique_ptr clone = - std::make_unique(var->name); - clone->line = var->line; - clone->column = var->column; - return clone; - } - if (auto bin = dynamic_cast(&expr)) { - std::unique_ptr left = cloneExpression(*bin->left); - std::unique_ptr right = cloneExpression(*bin->right); - std::unique_ptr clone = - std::make_unique(bin->op, std::move(left), std::move(right)); - clone->line = bin->line; - clone->column = bin->column; - return clone; - } - if (auto un = dynamic_cast(&expr)) { - std::unique_ptr right = cloneExpression(*un->right); - std::unique_ptr clone = - std::make_unique(un->op, std::move(right)); - clone->line = un->line; - clone->column = un->column; - return clone; - } - if (auto cast = dynamic_cast(&expr)) { - std::unique_ptr target; - if (cast->targetType) - target = cloneType(*cast->targetType); - std::unique_ptr inner = cloneExpression(*cast->expression); - std::unique_ptr clone = - std::make_unique(std::move(target), std::move(inner)); - clone->line = cast->line; - clone->column = cast->column; - return clone; - } - if (auto post = dynamic_cast(&expr)) { - std::unique_ptr left = cloneExpression(*post->left); - std::unique_ptr clone = - std::make_unique(post->op, std::move(left)); - clone->line = post->line; - clone->column = post->column; - return clone; - } - if (auto call = dynamic_cast(&expr)) { - std::unique_ptr callee = cloneExpression(*call->callee); - std::vector> args; - for (const auto& arg : call->arguments) { - args.push_back(cloneExpression(*arg)); - } - std::unique_ptr clone = - std::make_unique(std::move(callee), std::move(args)); - clone->line = call->line; - clone->column = call->column; - return clone; - } - if (auto member = dynamic_cast(&expr)) { - std::unique_ptr object = cloneExpression(*member->object); - std::unique_ptr clone = - std::make_unique(); - clone->object = std::move(object); - clone->member = member->member; - clone->line = member->line; - clone->column = member->column; - return clone; - } - if (auto newExpr = dynamic_cast(&expr)) { - std::unique_ptr classType; - if (newExpr->classType) - classType = cloneType(*newExpr->classType); - std::vector> args; - for (const auto& arg : newExpr->arguments) { - args.push_back(cloneExpression(*arg)); - } - std::unique_ptr clone = std::make_unique(); - clone->classType = std::move(classType); - clone->arguments = std::move(args); - clone->line = newExpr->line; - clone->column = newExpr->column; - return clone; - } - if (auto thisExpr = dynamic_cast(&expr)) { - std::unique_ptr clone = std::make_unique(); - clone->line = thisExpr->line; - clone->column = thisExpr->column; - return clone; - } - if (auto superExpr = dynamic_cast(&expr)) { - std::unique_ptr clone = std::make_unique(); - clone->line = superExpr->line; - clone->column = superExpr->column; - return clone; - } - if (auto idx = dynamic_cast(&expr)) { - std::unique_ptr collection = cloneExpression(*idx->collection); - std::unique_ptr index = cloneExpression(*idx->index); - std::unique_ptr clone = std::make_unique(); - clone->collection = std::move(collection); - clone->index = std::move(index); - clone->line = idx->line; - clone->column = idx->column; - return clone; - } - if (auto arr = dynamic_cast(&expr)) { - std::vector> elems; - for (const auto& el : arr->elements) { - elems.push_back(cloneExpression(*el)); - } - std::unique_ptr clone = - std::make_unique(std::move(elems)); - clone->line = arr->line; - clone->column = arr->column; - return clone; - } - if (auto par = dynamic_cast(&expr)) { - std::unique_ptr inner = cloneExpression(*par->expression); - std::unique_ptr clone = - std::make_unique(std::move(inner)); - clone->line = par->line; - clone->column = par->column; - return clone; - } - if (auto meas = dynamic_cast(&expr)) { - std::unique_ptr target = cloneExpression(*meas->qubit); - std::unique_ptr clone = - std::make_unique(std::move(target)); - clone->line = meas->line; - clone->column = meas->column; - return clone; - } - if (auto assign = dynamic_cast(&expr)) { - std::unique_ptr value = cloneExpression(*assign->value); - std::unique_ptr clone = std::make_unique( - AssignmentExpression{assign->name, std::move(value)}); - clone->line = assign->line; - clone->column = assign->column; - return clone; - } - if (auto memberAssign = dynamic_cast(&expr)) { - std::unique_ptr object = cloneExpression(*memberAssign->object); - std::unique_ptr value = cloneExpression(*memberAssign->value); - std::unique_ptr clone = - std::make_unique( - std::move(object), memberAssign->member, std::move(value)); - clone->line = memberAssign->line; - clone->column = memberAssign->column; - return clone; - } - if (auto arrAssign = dynamic_cast(&expr)) { - std::unique_ptr collection = cloneExpression(*arrAssign->collection); - std::unique_ptr index = cloneExpression(*arrAssign->index); - std::unique_ptr value = cloneExpression(*arrAssign->value); - std::unique_ptr clone = - std::make_unique(std::move(collection), std::move(index), - std::move(value)); - clone->line = arrAssign->line; - clone->column = arrAssign->column; - return clone; - } - return nullptr; - } + do { + args.push_back(parseExpression()); + } while (match(TokenType::Comma)); - std::unique_ptr Parser::cloneType(const Type& type) { - if (auto prim = dynamic_cast(&type)) - return std::make_unique(prim->name); - if (auto named = dynamic_cast(&type)) { - std::unique_ptr clone = std::make_unique(named->nameParts); - clone->hasTypeArgumentList = named->hasTypeArgumentList; - for (const auto& arg : named->typeArguments) { - clone->typeArguments.push_back(cloneType(*arg)); - } - clone->line = named->line; - clone->column = named->column; - return clone; - } - if (auto array = dynamic_cast(&type)) { - std::unique_ptr sizeExprClone; - if (array->sizeExpression) - sizeExprClone = cloneExpression(*array->sizeExpression); - std::unique_ptr clone = std::make_unique( - cloneType(*array->elementType), array->size, std::move(sizeExprClone)); - clone->line = array->line; - clone->column = array->column; - return clone; - } - if (dynamic_cast(&type)) - return std::make_unique(); - return nullptr; - } + return args; +} - std::vector> Parser::cloneAnnotations( - const std::vector>& annotations) { - std::vector> result; - for (const auto& ann : annotations) - result.push_back(std::make_unique(ann->name, ann->value)); - return result; +std::unique_ptr Parser::cloneExpression(const Expression& expr) { + if (auto lit = dynamic_cast(&expr)) { + std::unique_ptr clone = + std::make_unique(lit->value, lit->literalType); + clone->line = lit->line; + clone->column = lit->column; + return clone; } - - void Parser::flushExtraStatements(std::vector>& dest) { - for (auto& stmt : m_extraStatements) dest.push_back(std::move(stmt)); - m_extraStatements.clear(); + if (auto nullLit = dynamic_cast(&expr)) { + std::unique_ptr clone = std::make_unique(); + clone->line = nullLit->line; + clone->column = nullLit->column; + return clone; + } + if (auto var = dynamic_cast(&expr)) { + std::unique_ptr clone = std::make_unique(var->name); + clone->line = var->line; + clone->column = var->column; + return clone; + } + if (auto bin = dynamic_cast(&expr)) { + std::unique_ptr left = cloneExpression(*bin->left); + std::unique_ptr right = cloneExpression(*bin->right); + std::unique_ptr clone = + std::make_unique(bin->op, std::move(left), std::move(right)); + clone->line = bin->line; + clone->column = bin->column; + return clone; + } + if (auto un = dynamic_cast(&expr)) { + std::unique_ptr right = cloneExpression(*un->right); + std::unique_ptr clone = + std::make_unique(un->op, std::move(right)); + clone->line = un->line; + clone->column = un->column; + return clone; + } + if (auto cast = dynamic_cast(&expr)) { + std::unique_ptr target; + if (cast->targetType) + target = cloneType(*cast->targetType); + std::unique_ptr inner = cloneExpression(*cast->expression); + std::unique_ptr clone = + std::make_unique(std::move(target), std::move(inner)); + clone->line = cast->line; + clone->column = cast->column; + return clone; + } + if (auto post = dynamic_cast(&expr)) { + std::unique_ptr left = cloneExpression(*post->left); + std::unique_ptr clone = + std::make_unique(post->op, std::move(left)); + clone->line = post->line; + clone->column = post->column; + return clone; + } + if (auto call = dynamic_cast(&expr)) { + std::unique_ptr callee = cloneExpression(*call->callee); + std::vector> args; + for (const auto& arg : call->arguments) { + args.push_back(cloneExpression(*arg)); + } + std::unique_ptr clone = + std::make_unique(std::move(callee), std::move(args)); + clone->line = call->line; + clone->column = call->column; + return clone; + } + if (auto member = dynamic_cast(&expr)) { + std::unique_ptr object = cloneExpression(*member->object); + std::unique_ptr clone = std::make_unique(); + clone->object = std::move(object); + clone->member = member->member; + clone->line = member->line; + clone->column = member->column; + return clone; + } + if (auto newExpr = dynamic_cast(&expr)) { + std::unique_ptr classType; + if (newExpr->classType) + classType = cloneType(*newExpr->classType); + std::vector> args; + for (const auto& arg : newExpr->arguments) { + args.push_back(cloneExpression(*arg)); + } + std::unique_ptr clone = std::make_unique(); + clone->classType = std::move(classType); + clone->arguments = std::move(args); + clone->line = newExpr->line; + clone->column = newExpr->column; + return clone; + } + if (auto thisExpr = dynamic_cast(&expr)) { + std::unique_ptr clone = std::make_unique(); + clone->line = thisExpr->line; + clone->column = thisExpr->column; + return clone; + } + if (auto superExpr = dynamic_cast(&expr)) { + std::unique_ptr clone = std::make_unique(); + clone->line = superExpr->line; + clone->column = superExpr->column; + return clone; + } + if (auto idx = dynamic_cast(&expr)) { + std::unique_ptr collection = cloneExpression(*idx->collection); + std::unique_ptr index = cloneExpression(*idx->index); + std::unique_ptr clone = std::make_unique(); + clone->collection = std::move(collection); + clone->index = std::move(index); + clone->line = idx->line; + clone->column = idx->column; + return clone; + } + if (auto arr = dynamic_cast(&expr)) { + std::vector> elems; + for (const auto& el : arr->elements) { + elems.push_back(cloneExpression(*el)); + } + std::unique_ptr clone = + std::make_unique(std::move(elems)); + clone->line = arr->line; + clone->column = arr->column; + return clone; + } + if (auto par = dynamic_cast(&expr)) { + std::unique_ptr inner = cloneExpression(*par->expression); + std::unique_ptr clone = + std::make_unique(std::move(inner)); + clone->line = par->line; + clone->column = par->column; + return clone; + } + if (auto meas = dynamic_cast(&expr)) { + std::unique_ptr target = cloneExpression(*meas->qubit); + std::unique_ptr clone = + std::make_unique(std::move(target)); + clone->line = meas->line; + clone->column = meas->column; + return clone; + } + if (auto assign = dynamic_cast(&expr)) { + std::unique_ptr value = cloneExpression(*assign->value); + std::unique_ptr clone = std::make_unique( + AssignmentExpression{assign->name, std::move(value)}); + clone->line = assign->line; + clone->column = assign->column; + return clone; + } + if (auto memberAssign = dynamic_cast(&expr)) { + std::unique_ptr object = cloneExpression(*memberAssign->object); + std::unique_ptr value = cloneExpression(*memberAssign->value); + std::unique_ptr clone = + std::make_unique(std::move(object), memberAssign->member, + std::move(value)); + clone->line = memberAssign->line; + clone->column = memberAssign->column; + return clone; + } + if (auto arrAssign = dynamic_cast(&expr)) { + std::unique_ptr collection = cloneExpression(*arrAssign->collection); + std::unique_ptr index = cloneExpression(*arrAssign->index); + std::unique_ptr value = cloneExpression(*arrAssign->value); + std::unique_ptr clone = + std::make_unique(std::move(collection), std::move(index), + std::move(value)); + clone->line = arrAssign->line; + clone->column = arrAssign->column; + return clone; + } + return nullptr; +} + +std::unique_ptr Parser::cloneType(const Type& type) { + if (auto prim = dynamic_cast(&type)) + return std::make_unique(prim->name); + if (auto named = dynamic_cast(&type)) { + std::unique_ptr clone = std::make_unique(named->nameParts); + clone->hasTypeArgumentList = named->hasTypeArgumentList; + for (const auto& arg : named->typeArguments) { + clone->typeArguments.push_back(cloneType(*arg)); + } + clone->line = named->line; + clone->column = named->column; + return clone; + } + if (auto array = dynamic_cast(&type)) { + std::unique_ptr sizeExprClone; + if (array->sizeExpression) + sizeExprClone = cloneExpression(*array->sizeExpression); + std::unique_ptr clone = std::make_unique( + cloneType(*array->elementType), array->size, std::move(sizeExprClone)); + clone->line = array->line; + clone->column = array->column; + return clone; } + if (dynamic_cast(&type)) + return std::make_unique(); + return nullptr; +} + +std::vector> Parser::cloneAnnotations( + const std::vector>& annotations) { + std::vector> result; + for (const auto& ann : annotations) + result.push_back(std::make_unique(ann->name, ann->value)); + return result; +} + +void Parser::flushExtraStatements(std::vector>& dest) { + for (auto& stmt : m_extraStatements) + dest.push_back(std::move(stmt)); + m_extraStatements.clear(); +} } // namespace bloch::compiler diff --git a/src/bloch/compiler/parser/parser.hpp b/src/bloch/compiler/parser/parser.hpp index 3622abf..78b04d7 100644 --- a/src/bloch/compiler/parser/parser.hpp +++ b/src/bloch/compiler/parser/parser.hpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,121 +22,119 @@ #include "bloch/compiler/lexer/token.hpp" namespace bloch::compiler { - /** - * Parser consumes a flat token stream and produces an AST. - * - * Design notes (living doc): - * - Statements and declarations stay hand-written for clarity. - * - Expressions use a Pratt/precedence-table loop (see parser.cpp) to avoid - * the N-level cascade of parse* methods and make adding operators table-driven. - * - Multi-declarations (e.g., `qubit a, b;`) are expanded via m_extraStatements. - * - Errors throw BlochError with 1-based line/column taken from tokens. - */ - class Parser { - public: - explicit Parser(std::vector tokens); - [[nodiscard]] std::unique_ptr parse(); - - private: - std::vector m_tokens; - size_t m_current; - // For multi-declarations (e.g. qubit a, b, c;), we parse the first - // and stage the rest here, then flush them into the surrounding block. - std::vector> m_extraStatements; - - // Token manipulation - [[nodiscard]] const Token& peek() const; - [[nodiscard]] const Token& previous() const; - [[nodiscard]] const Token& advance(); - [[nodiscard]] const Token& expect(TokenType type, const std::string& message); - - // Token matching - [[nodiscard]] bool match(TokenType type); - [[nodiscard]] bool check(TokenType type) const; - [[nodiscard]] bool checkNext(TokenType type) const; - [[nodiscard]] bool checkFunctionAnnotation() const; - [[nodiscard]] bool isTypeAhead() const; - [[nodiscard]] bool isAtEnd() const; - - void reportError(const std::string& msg); - - // Top level - [[nodiscard]] std::unique_ptr parsePackageDeclaration(); - [[nodiscard]] std::unique_ptr parseImport(); - [[nodiscard]] std::unique_ptr parseClassDeclaration(); - [[nodiscard]] std::unique_ptr parseFunction(); - - // Declarations - [[nodiscard]] std::unique_ptr parseClassMember(const std::string& className, - bool isStaticClass); - [[nodiscard]] std::unique_ptr parseFieldDeclaration( - Visibility vis, bool isFinal, bool isStatic, - std::vector> annotations); - [[nodiscard]] std::unique_ptr parseMethodDeclaration( - Visibility vis, bool isStatic, bool isVirtual, bool isOverride, - std::vector> annotations); - [[nodiscard]] std::unique_ptr parseConstructorDeclaration( - Visibility vis, const std::string& className); - [[nodiscard]] std::unique_ptr parseDestructorDeclaration( - Visibility vis); - [[nodiscard]] Visibility parseVisibility(); - [[nodiscard]] std::vector parseQualifiedName(); - [[nodiscard]] std::unique_ptr parseVariableDeclaration( - bool isFinal, bool allowMultiple = true); - [[nodiscard]] std::unique_ptr parseVariableDeclaration( - std::unique_ptr preParsedType, bool isFinal, bool allowMultiple = true); - [[nodiscard]] std::unique_ptr parseVariableAnnotation(); - [[nodiscard]] std::unique_ptr parseFunctionAnnotation(); - [[nodiscard]] std::vector> parseAnnotations(); - - // Statements - [[nodiscard]] std::unique_ptr parseStatement(); - [[nodiscard]] std::unique_ptr parseBlock(); - [[nodiscard]] std::unique_ptr parseReturn(); - [[nodiscard]] std::unique_ptr parseIf(); - [[nodiscard]] std::unique_ptr parseFor(); - [[nodiscard]] std::unique_ptr parseWhile(); - [[nodiscard]] std::unique_ptr parseEcho(); - [[nodiscard]] std::unique_ptr parseReset(); - [[nodiscard]] std::unique_ptr parseMeasure(); - [[nodiscard]] std::unique_ptr parseDestroy(); - [[nodiscard]] std::unique_ptr parseAssignment(); - [[nodiscard]] std::unique_ptr parseExpressionStatement(); - - // Expressions - [[nodiscard]] std::unique_ptr parseExpression(); - [[nodiscard]] std::unique_ptr parseAssignmentExpression(); - /** Pratt-style expression parser using binding powers (see parser.cpp). */ - [[nodiscard]] std::unique_ptr parsePrattExpression(int minBp); - /** Parses prefix operators (unary) and primaries; postfix handled in Pratt loop. */ - [[nodiscard]] std::unique_ptr parsePrefixExpression(); - /** Compatibility wrapper for cast operands; equivalent to prefix expression parse. */ - [[nodiscard]] std::unique_ptr parseUnary(); - [[nodiscard]] std::unique_ptr parsePrimary(); - [[nodiscard]] std::unique_ptr parseArrayLiteral(); - - // Literals - [[nodiscard]] std::unique_ptr parseLiteral(); - - // Types - [[nodiscard]] std::unique_ptr parseType(bool allowEmptyTypeArguments = false); - [[nodiscard]] std::unique_ptr parsePrimitiveType(); - [[nodiscard]] std::unique_ptr parseArrayType( - std::unique_ptr elementType, int size = -1, - std::unique_ptr sizeExpr = nullptr); - [[nodiscard]] std::vector> parseTypeParameters(); - [[nodiscard]] std::vector> parseTypeArgumentList( - bool allowEmpty = false); - - // Parameters and Arguments - [[nodiscard]] std::vector> parseParameterList(); - [[nodiscard]] std::vector> parseArgumentList(); - - // Helpers - [[nodiscard]] std::unique_ptr cloneExpression(const Expression& expr); - [[nodiscard]] std::unique_ptr cloneType(const Type& type); - [[nodiscard]] std::vector> cloneAnnotations( - const std::vector>& annotations); - void flushExtraStatements(std::vector>& dest); - }; +/** + * Parser consumes a flat token stream and produces an AST. + * + * Design notes (living doc): + * - Statements and declarations stay hand-written for clarity. + * - Expressions use a Pratt/precedence-table loop (see parser.cpp) to avoid + * the N-level cascade of parse* methods and make adding operators table-driven. + * - Multi-declarations (e.g., `qubit a, b;`) are expanded via m_extraStatements. + * - Errors throw BlochError with 1-based line/column taken from tokens. + */ +class Parser { + public: + explicit Parser(std::vector tokens); + [[nodiscard]] std::unique_ptr parse(); + + private: + std::vector m_tokens; + size_t m_current; + // For multi-declarations (e.g. qubit a, b, c;), we parse the first + // and stage the rest here, then flush them into the surrounding block. + std::vector> m_extraStatements; + + // Token manipulation + [[nodiscard]] const Token& peek() const; + [[nodiscard]] const Token& previous() const; + [[nodiscard]] const Token& advance(); + [[nodiscard]] const Token& expect(TokenType type, const std::string& message); + + // Token matching + [[nodiscard]] bool match(TokenType type); + [[nodiscard]] bool check(TokenType type) const; + [[nodiscard]] bool checkNext(TokenType type) const; + [[nodiscard]] bool checkFunctionAnnotation() const; + [[nodiscard]] bool isTypeAhead() const; + [[nodiscard]] bool isAtEnd() const; + + void reportError(const std::string& msg); + + // Top level + [[nodiscard]] std::unique_ptr parsePackageDeclaration(); + [[nodiscard]] std::unique_ptr parseImport(); + [[nodiscard]] std::unique_ptr parseClassDeclaration(); + [[nodiscard]] std::unique_ptr parseFunction(); + + // Declarations + [[nodiscard]] std::unique_ptr parseClassMember(const std::string& className, + bool isStaticClass); + [[nodiscard]] std::unique_ptr parseFieldDeclaration( + Visibility vis, bool isFinal, bool isStatic, + std::vector> annotations); + [[nodiscard]] std::unique_ptr parseMethodDeclaration( + Visibility vis, bool isStatic, bool isVirtual, bool isOverride, + std::vector> annotations); + [[nodiscard]] std::unique_ptr parseConstructorDeclaration( + Visibility vis, const std::string& className); + [[nodiscard]] std::unique_ptr parseDestructorDeclaration(Visibility vis); + [[nodiscard]] Visibility parseVisibility(); + [[nodiscard]] std::vector parseQualifiedName(); + [[nodiscard]] std::unique_ptr parseVariableDeclaration( + bool isFinal, bool allowMultiple = true); + [[nodiscard]] std::unique_ptr parseVariableDeclaration( + std::unique_ptr preParsedType, bool isFinal, bool allowMultiple = true); + [[nodiscard]] std::unique_ptr parseVariableAnnotation(); + [[nodiscard]] std::unique_ptr parseFunctionAnnotation(); + [[nodiscard]] std::vector> parseAnnotations(); + + // Statements + [[nodiscard]] std::unique_ptr parseStatement(); + [[nodiscard]] std::unique_ptr parseBlock(); + [[nodiscard]] std::unique_ptr parseReturn(); + [[nodiscard]] std::unique_ptr parseIf(); + [[nodiscard]] std::unique_ptr parseFor(); + [[nodiscard]] std::unique_ptr parseWhile(); + [[nodiscard]] std::unique_ptr parseEcho(); + [[nodiscard]] std::unique_ptr parseReset(); + [[nodiscard]] std::unique_ptr parseMeasure(); + [[nodiscard]] std::unique_ptr parseDestroy(); + [[nodiscard]] std::unique_ptr parseAssignment(); + [[nodiscard]] std::unique_ptr parseExpressionStatement(); + + // Expressions + [[nodiscard]] std::unique_ptr parseExpression(); + [[nodiscard]] std::unique_ptr parseAssignmentExpression(); + /** Pratt-style expression parser using binding powers (see parser.cpp). */ + [[nodiscard]] std::unique_ptr parsePrattExpression(int minBp); + /** Parses prefix operators (unary) and primaries; postfix handled in Pratt loop. */ + [[nodiscard]] std::unique_ptr parsePrefixExpression(); + /** Compatibility wrapper for cast operands; equivalent to prefix expression parse. */ + [[nodiscard]] std::unique_ptr parseUnary(); + [[nodiscard]] std::unique_ptr parsePrimary(); + [[nodiscard]] std::unique_ptr parseArrayLiteral(); + + // Literals + [[nodiscard]] std::unique_ptr parseLiteral(); + + // Types + [[nodiscard]] std::unique_ptr parseType(bool allowEmptyTypeArguments = false); + [[nodiscard]] std::unique_ptr parsePrimitiveType(); + [[nodiscard]] std::unique_ptr parseArrayType( + std::unique_ptr elementType, int size = -1, + std::unique_ptr sizeExpr = nullptr); + [[nodiscard]] std::vector> parseTypeParameters(); + [[nodiscard]] std::vector> parseTypeArgumentList(bool allowEmpty = false); + + // Parameters and Arguments + [[nodiscard]] std::vector> parseParameterList(); + [[nodiscard]] std::vector> parseArgumentList(); + + // Helpers + [[nodiscard]] std::unique_ptr cloneExpression(const Expression& expr); + [[nodiscard]] std::unique_ptr cloneType(const Type& type); + [[nodiscard]] std::vector> cloneAnnotations( + const std::vector>& annotations); + void flushExtraStatements(std::vector>& dest); +}; } // namespace bloch::compiler diff --git a/src/bloch/compiler/semantics/built_ins.cpp b/src/bloch/compiler/semantics/built_ins.cpp index e330f42..b551e06 100644 --- a/src/bloch/compiler/semantics/built_ins.cpp +++ b/src/bloch/compiler/semantics/built_ins.cpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,15 +16,15 @@ namespace bloch::compiler { - const std::unordered_map builtInGates = { - {"h", BuiltInGate{"h", {ValueType::Qubit}, ValueType::Void}}, - {"x", BuiltInGate{"x", {ValueType::Qubit}, ValueType::Void}}, - {"y", BuiltInGate{"y", {ValueType::Qubit}, ValueType::Void}}, - {"z", BuiltInGate{"z", {ValueType::Qubit}, ValueType::Void}}, - {"rx", BuiltInGate{"rx", {ValueType::Qubit, ValueType::Float}, ValueType::Void}}, - {"ry", BuiltInGate{"ry", {ValueType::Qubit, ValueType::Float}, ValueType::Void}}, - {"rz", BuiltInGate{"rz", {ValueType::Qubit, ValueType::Float}, ValueType::Void}}, - {"cx", BuiltInGate{"cx", {ValueType::Qubit, ValueType::Qubit}, ValueType::Void}}, - }; +const std::unordered_map builtInGates = { + {"h", BuiltInGate{"h", {ValueType::Qubit}, ValueType::Void}}, + {"x", BuiltInGate{"x", {ValueType::Qubit}, ValueType::Void}}, + {"y", BuiltInGate{"y", {ValueType::Qubit}, ValueType::Void}}, + {"z", BuiltInGate{"z", {ValueType::Qubit}, ValueType::Void}}, + {"rx", BuiltInGate{"rx", {ValueType::Qubit, ValueType::Float}, ValueType::Void}}, + {"ry", BuiltInGate{"ry", {ValueType::Qubit, ValueType::Float}, ValueType::Void}}, + {"rz", BuiltInGate{"rz", {ValueType::Qubit, ValueType::Float}, ValueType::Void}}, + {"cx", BuiltInGate{"cx", {ValueType::Qubit, ValueType::Qubit}, ValueType::Void}}, +}; } // namespace bloch::compiler diff --git a/src/bloch/compiler/semantics/built_ins.hpp b/src/bloch/compiler/semantics/built_ins.hpp index e051f0c..0b23e01 100644 --- a/src/bloch/compiler/semantics/built_ins.hpp +++ b/src/bloch/compiler/semantics/built_ins.hpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,15 +17,16 @@ #include #include #include + #include "bloch/compiler/semantics/type_system.hpp" namespace bloch::compiler { - // Built-in gate signatures used by the semantic pass and runtime dispatch. - struct BuiltInGate { - std::string name; - std::vector paramTypes; - ValueType returnType; - }; +// Built-in gate signatures used by the semantic pass and runtime dispatch. +struct BuiltInGate { + std::string name; + std::vector paramTypes; + ValueType returnType; +}; - extern const std::unordered_map builtInGates; +extern const std::unordered_map builtInGates; } // namespace bloch::compiler diff --git a/src/bloch/compiler/semantics/semantic_analyser.cpp b/src/bloch/compiler/semantics/semantic_analyser.cpp index 16fd9b2..89a8828 100644 --- a/src/bloch/compiler/semantics/semantic_analyser.cpp +++ b/src/bloch/compiler/semantics/semantic_analyser.cpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -25,2338 +25,2212 @@ namespace bloch::compiler { - using support::BlochError; - using support::ErrorCategory; +using support::BlochError; +using support::ErrorCategory; - SemanticAnalyser::TypeInfo SemanticAnalyser::combine(ValueType prim, const std::string& cls) { - TypeInfo t; - t.value = prim; - t.className = cls; - return t; - } +SemanticAnalyser::TypeInfo SemanticAnalyser::combine(ValueType prim, const std::string& cls) { + TypeInfo t; + t.value = prim; + t.className = cls; + return t; +} - bool SemanticAnalyser::typeEquals(const TypeInfo& a, const TypeInfo& b) { - if (a.isTypeParam || b.isTypeParam) - return a.isTypeParam && b.isTypeParam && a.className == b.className; - if (a.value != b.value) - return false; - if (a.className != b.className) - return false; - if (a.typeArgs.size() != b.typeArgs.size()) +bool SemanticAnalyser::typeEquals(const TypeInfo& a, const TypeInfo& b) { + if (a.isTypeParam || b.isTypeParam) + return a.isTypeParam && b.isTypeParam && a.className == b.className; + if (a.value != b.value) + return false; + if (a.className != b.className) + return false; + if (a.typeArgs.size() != b.typeArgs.size()) + return false; + for (size_t i = 0; i < a.typeArgs.size(); ++i) { + if (!typeEquals(a.typeArgs[i], b.typeArgs[i])) return false; - for (size_t i = 0; i < a.typeArgs.size(); ++i) { - if (!typeEquals(a.typeArgs[i], b.typeArgs[i])) - return false; - } - return true; - } - - std::string SemanticAnalyser::typeLabel(const TypeInfo& t) { - if (t.isTypeParam) - return t.className; - auto isArray = [](const std::string& name) { - return name.size() >= 2 && name.rfind("[]") == name.size() - 2; - }; - if (isArray(t.className) && !t.typeArgs.empty()) { - return typeLabel(t.typeArgs.front()) + "[]"; - } - if (!t.className.empty()) { - std::string res = t.className; - if (!t.typeArgs.empty()) { - res += "<"; - for (size_t i = 0; i < t.typeArgs.size(); ++i) { - if (i) - res += ","; - res += typeLabel(t.typeArgs[i]); - } - res += ">"; - } - return res; - } - return typeToString(t.value); } - - namespace { - template - class ScopeExit { - public: - explicit ScopeExit(Fn&& fn) : m_fn(std::forward(fn)) {} - ~ScopeExit() { m_fn(); } - ScopeExit(const ScopeExit&) = delete; - ScopeExit& operator=(const ScopeExit&) = delete; - - private: - Fn m_fn; - }; - - template - ScopeExit makeScopeExit(Fn&& fn) { - return ScopeExit(std::forward(fn)); - } - - std::string methodSignatureLabel(const std::string& name, - const std::vector& params) { - std::ostringstream oss; - oss << name << "("; - for (size_t i = 0; i < params.size(); ++i) { + return true; +} + +std::string SemanticAnalyser::typeLabel(const TypeInfo& t) { + if (t.isTypeParam) + return t.className; + auto isArray = [](const std::string& name) { + return name.size() >= 2 && name.rfind("[]") == name.size() - 2; + }; + if (isArray(t.className) && !t.typeArgs.empty()) { + return typeLabel(t.typeArgs.front()) + "[]"; + } + if (!t.className.empty()) { + std::string res = t.className; + if (!t.typeArgs.empty()) { + res += "<"; + for (size_t i = 0; i < t.typeArgs.size(); ++i) { if (i) - oss << ","; - oss << SemanticAnalyser::typeLabel(params[i]); - } - oss << ")"; - return oss.str(); - } - - bool paramTypesEqual(const std::vector& a, - const std::vector& b) { - if (a.size() != b.size()) - return false; - for (size_t i = 0; i < a.size(); ++i) { - if (!SemanticAnalyser::typeEquals(a[i], b[i])) - return false; + res += ","; + res += typeLabel(t.typeArgs[i]); } - return true; + res += ">"; } - - auto numericPromotion = [](ValueType a, ValueType b) { - if (a == ValueType::Float || b == ValueType::Float) - return ValueType::Float; - if (a == ValueType::Long || b == ValueType::Long) - return ValueType::Long; - if (a == ValueType::Int || b == ValueType::Int) - return ValueType::Int; - if (a == ValueType::Bit || b == ValueType::Bit) - return ValueType::Bit; - return ValueType::Unknown; - }; - - auto matchesPrimitive = [](ValueType expected, ValueType actual) { - if (expected == ValueType::Unknown || actual == ValueType::Unknown) - return true; - if (expected == actual) - return true; - if (expected == ValueType::Long && actual == ValueType::Int) - return true; // widening + return res; + } + return typeToString(t.value); +} + +namespace { +template +class ScopeExit { + public: + explicit ScopeExit(Fn&& fn) : m_fn(std::forward(fn)) {} + ~ScopeExit() { m_fn(); } + ScopeExit(const ScopeExit&) = delete; + ScopeExit& operator=(const ScopeExit&) = delete; + + private: + Fn m_fn; +}; + +template +ScopeExit makeScopeExit(Fn&& fn) { + return ScopeExit(std::forward(fn)); +} + +std::string methodSignatureLabel(const std::string& name, + const std::vector& params) { + std::ostringstream oss; + oss << name << "("; + for (size_t i = 0; i < params.size(); ++i) { + if (i) + oss << ","; + oss << SemanticAnalyser::typeLabel(params[i]); + } + oss << ")"; + return oss.str(); +} + +bool paramTypesEqual(const std::vector& a, + const std::vector& b) { + if (a.size() != b.size()) + return false; + for (size_t i = 0; i < a.size(); ++i) { + if (!SemanticAnalyser::typeEquals(a[i], b[i])) return false; - }; - - bool isArrayTypeName(const std::string& name) { - return name.size() >= 2 && name.rfind("[]") == name.size() - 2; - } - - bool isArrayType(const SemanticAnalyser::TypeInfo& t) { - return !t.className.empty() && isArrayTypeName(t.className); - } - - bool isClassRefType(const SemanticAnalyser::TypeInfo& t) { - return !t.className.empty() && !isArrayTypeName(t.className); - } - - bool isNumericPrimitive(ValueType v) { - return v == ValueType::Int || v == ValueType::Long || v == ValueType::Float; - } - - bool isNumericType(const SemanticAnalyser::TypeInfo& t) { - return t.className.empty() && isNumericPrimitive(t.value); - } - - bool isBooleanLike(const SemanticAnalyser::TypeInfo& t) { - return t.className.empty() && - (t.value == ValueType::Boolean || t.value == ValueType::Bit); - } - - bool isBitArrayType(const SemanticAnalyser::TypeInfo& t) { - return isArrayType(t) && !t.typeArgs.empty() && t.typeArgs[0].className.empty() && - t.typeArgs[0].value == ValueType::Bit; - } - } // namespace - - SemanticAnalyser::TypeInfo SemanticAnalyser::typeFromAst(Type* typeNode) const { - if (!typeNode) - return combine(ValueType::Unknown, ""); - if (auto prim = dynamic_cast(typeNode)) - return combine(typeFromString(prim->name), ""); - if (auto named = dynamic_cast(typeNode)) { - std::string cls = named->nameParts.empty() ? "" : named->nameParts.back(); - if (!m_inClassRegistryBuild && named->hasTypeArgumentList && - named->typeArguments.empty()) { - const ClassInfo* info = findClass(cls); - if (info && info->typeParams.empty()) { - throw BlochError(ErrorCategory::Semantic, named->line, named->column, - "type '" + cls + "' is not generic"); - } + } + return true; +} + +auto numericPromotion = [](ValueType a, ValueType b) { + if (a == ValueType::Float || b == ValueType::Float) + return ValueType::Float; + if (a == ValueType::Long || b == ValueType::Long) + return ValueType::Long; + if (a == ValueType::Int || b == ValueType::Int) + return ValueType::Int; + if (a == ValueType::Bit || b == ValueType::Bit) + return ValueType::Bit; + return ValueType::Unknown; +}; + +auto matchesPrimitive = [](ValueType expected, ValueType actual) { + if (expected == ValueType::Unknown || actual == ValueType::Unknown) + return true; + if (expected == actual) + return true; + if (expected == ValueType::Long && actual == ValueType::Int) + return true; // widening + return false; +}; + +bool isArrayTypeName(const std::string& name) { + return name.size() >= 2 && name.rfind("[]") == name.size() - 2; +} + +bool isArrayType(const SemanticAnalyser::TypeInfo& t) { + return !t.className.empty() && isArrayTypeName(t.className); +} + +bool isClassRefType(const SemanticAnalyser::TypeInfo& t) { + return !t.className.empty() && !isArrayTypeName(t.className); +} + +bool isNumericPrimitive(ValueType v) { + return v == ValueType::Int || v == ValueType::Long || v == ValueType::Float; +} + +bool isNumericType(const SemanticAnalyser::TypeInfo& t) { + return t.className.empty() && isNumericPrimitive(t.value); +} + +bool isBooleanLike(const SemanticAnalyser::TypeInfo& t) { + return t.className.empty() && (t.value == ValueType::Boolean || t.value == ValueType::Bit); +} + +bool isBitArrayType(const SemanticAnalyser::TypeInfo& t) { + return isArrayType(t) && !t.typeArgs.empty() && t.typeArgs[0].className.empty() && + t.typeArgs[0].value == ValueType::Bit; +} +} // namespace + +SemanticAnalyser::TypeInfo SemanticAnalyser::typeFromAst(Type* typeNode) const { + if (!typeNode) + return combine(ValueType::Unknown, ""); + if (auto prim = dynamic_cast(typeNode)) + return combine(typeFromString(prim->name), ""); + if (auto named = dynamic_cast(typeNode)) { + std::string cls = named->nameParts.empty() ? "" : named->nameParts.back(); + if (!m_inClassRegistryBuild && named->hasTypeArgumentList && named->typeArguments.empty()) { + const ClassInfo* info = findClass(cls); + if (info && info->typeParams.empty()) { throw BlochError(ErrorCategory::Semantic, named->line, named->column, - "cannot infer type arguments for '" + cls + "' in this context"); - } - for (const auto& tp : m_currentTypeParams) { - if (tp.name == cls) { - TypeInfo t = combine(ValueType::Unknown, cls); - t.isTypeParam = true; - return t; - } + "type '" + cls + "' is not generic"); } - TypeInfo t = combine(ValueType::Unknown, cls); - for (const auto& arg : named->typeArguments) { - t.typeArgs.push_back(typeFromAst(arg.get())); + throw BlochError(ErrorCategory::Semantic, named->line, named->column, + "cannot infer type arguments for '" + cls + "' in this context"); + } + for (const auto& tp : m_currentTypeParams) { + if (tp.name == cls) { + TypeInfo t = combine(ValueType::Unknown, cls); + t.isTypeParam = true; + return t; } - if (!m_inClassRegistryBuild) - validateTypeApplication(t, named->line, named->column); - return t; - } - if (dynamic_cast(typeNode)) - return combine(ValueType::Void, ""); - if (auto arr = dynamic_cast(typeNode)) { - auto elem = typeFromAst(arr->elementType.get()); - std::string base = elem.className.empty() ? typeToString(elem.value) : elem.className; - TypeInfo t = combine(ValueType::Unknown, base + "[]"); - t.typeArgs.clear(); - t.typeArgs.push_back(elem); - return t; } - return combine(ValueType::Unknown, ""); + TypeInfo t = combine(ValueType::Unknown, cls); + for (const auto& arg : named->typeArguments) { + t.typeArgs.push_back(typeFromAst(arg.get())); + } + if (!m_inClassRegistryBuild) + validateTypeApplication(t, named->line, named->column); + return t; } - - const SemanticAnalyser::ClassInfo* SemanticAnalyser::findClass(const std::string& name) const { - auto it = m_classes.find(name); - if (it != m_classes.end()) - return &it->second; - return nullptr; + if (dynamic_cast(typeNode)) + return combine(ValueType::Void, ""); + if (auto arr = dynamic_cast(typeNode)) { + auto elem = typeFromAst(arr->elementType.get()); + std::string base = elem.className.empty() ? typeToString(elem.value) : elem.className; + TypeInfo t = combine(ValueType::Unknown, base + "[]"); + t.typeArgs.clear(); + t.typeArgs.push_back(elem); + return t; } - - SemanticAnalyser::TypeInfo SemanticAnalyser::substituteTypeParams( - const TypeInfo& t, const std::vector& params, - const std::vector& args) const { - if (t.isTypeParam) { - for (size_t i = 0; i < params.size(); ++i) { - if (params[i].name == t.className && i < args.size()) - return args[i]; + return combine(ValueType::Unknown, ""); +} + +const SemanticAnalyser::ClassInfo* SemanticAnalyser::findClass(const std::string& name) const { + auto it = m_classes.find(name); + if (it != m_classes.end()) + return &it->second; + return nullptr; +} + +SemanticAnalyser::TypeInfo SemanticAnalyser::substituteTypeParams( + const TypeInfo& t, const std::vector& params, + const std::vector& args) const { + if (t.isTypeParam) { + for (size_t i = 0; i < params.size(); ++i) { + if (params[i].name == t.className && i < args.size()) + return args[i]; + } + } + TypeInfo out = t; + out.typeArgs.clear(); + for (const auto& a : t.typeArgs) + out.typeArgs.push_back(substituteTypeParams(a, params, args)); + auto isArray = [](const std::string& name) { + return name.size() >= 2 && name.rfind("[]") == name.size() - 2; + }; + if (isArray(out.className) && !out.typeArgs.empty()) { + out.className = typeLabel(out.typeArgs.front()) + "[]"; + } + return out; +} + +std::vector SemanticAnalyser::substituteMany( + const std::vector& types, const std::vector& params, + const std::vector& args) const { + std::vector res; + res.reserve(types.size()); + for (const auto& t : types) + res.push_back(substituteTypeParams(t, params, args)); + return res; +} + +void SemanticAnalyser::validateTypeApplication(const TypeInfo& t, int line, int column) const { + for (const auto& arg : t.typeArgs) + validateTypeApplication(arg, line, column); + if (t.className.empty()) + return; + const ClassInfo* info = findClass(t.className); + if (!info) + return; + if (info->typeParams.size() != t.typeArgs.size()) { + throw BlochError(ErrorCategory::Semantic, line, column, + "type '" + t.className + "' expects " + + std::to_string(info->typeParams.size()) + " type argument(s)"); + } + for (size_t i = 0; i < info->typeParams.size() && i < t.typeArgs.size(); ++i) { + const auto& bound = info->typeParams[i].bound; + TypeInfo actual = t.typeArgs[i]; + if (!bound.className.empty() && actual.isTypeParam) { + auto actualBound = getTypeParamBound(actual.className); + if (!actualBound) { + throw BlochError(ErrorCategory::Semantic, line, column, + "type parameter '" + actual.className + + "' does not satisfy bound '" + typeLabel(bound) + "'"); } + actual = *actualBound; } - TypeInfo out = t; - out.typeArgs.clear(); - for (const auto& a : t.typeArgs) - out.typeArgs.push_back(substituteTypeParams(a, params, args)); - auto isArray = [](const std::string& name) { - return name.size() >= 2 && name.rfind("[]") == name.size() - 2; - }; - if (isArray(out.className) && !out.typeArgs.empty()) { - out.className = typeLabel(out.typeArgs.front()) + "[]"; - } - return out; - } - - std::vector SemanticAnalyser::substituteMany( - const std::vector& types, const std::vector& params, - const std::vector& args) const { - std::vector res; - res.reserve(types.size()); - for (const auto& t : types) res.push_back(substituteTypeParams(t, params, args)); - return res; - } - - void SemanticAnalyser::validateTypeApplication(const TypeInfo& t, int line, int column) const { - for (const auto& arg : t.typeArgs) validateTypeApplication(arg, line, column); - if (t.className.empty()) - return; - const ClassInfo* info = findClass(t.className); - if (!info) - return; - if (info->typeParams.size() != t.typeArgs.size()) { - throw BlochError(ErrorCategory::Semantic, line, column, - "type '" + t.className + "' expects " + - std::to_string(info->typeParams.size()) + " type argument(s)"); - } - for (size_t i = 0; i < info->typeParams.size() && i < t.typeArgs.size(); ++i) { - const auto& bound = info->typeParams[i].bound; - TypeInfo actual = t.typeArgs[i]; - if (!bound.className.empty() && actual.isTypeParam) { - auto actualBound = getTypeParamBound(actual.className); - if (!actualBound) { - throw BlochError(ErrorCategory::Semantic, line, column, - "type parameter '" + actual.className + - "' does not satisfy bound '" + typeLabel(bound) + "'"); - } - actual = *actualBound; + if (!bound.className.empty()) { + if (actual.className.empty()) { + throw BlochError(ErrorCategory::Semantic, line, column, + "type argument '" + typeLabel(actual) + + "' does not satisfy bound '" + typeLabel(bound) + "'"); } - if (!bound.className.empty()) { - if (actual.className.empty()) { - throw BlochError(ErrorCategory::Semantic, line, column, - "type argument '" + typeLabel(actual) + - "' does not satisfy bound '" + typeLabel(bound) + "'"); - } - if ((actual.className == bound.className && !typeEquals(actual, bound)) || - (actual.className != bound.className && - !isSubclassOf(actual.className, bound.className))) { - throw BlochError(ErrorCategory::Semantic, line, column, - "type argument '" + typeLabel(actual) + - "' does not satisfy bound '" + typeLabel(bound) + "'"); - } + if ((actual.className == bound.className && !typeEquals(actual, bound)) || + (actual.className != bound.className && + !isSubclassOf(actual.className, bound.className))) { + throw BlochError(ErrorCategory::Semantic, line, column, + "type argument '" + typeLabel(actual) + + "' does not satisfy bound '" + typeLabel(bound) + "'"); } } } +} - std::optional SemanticAnalyser::getTypeParamBound( - const std::string& name) const { - for (const auto& tp : m_currentTypeParams) { - if (tp.name == name) { - if (tp.bound.className.empty() && tp.bound.value == ValueType::Unknown && - tp.bound.typeArgs.empty()) - return std::nullopt; - return tp.bound; - } +std::optional SemanticAnalyser::getTypeParamBound( + const std::string& name) const { + for (const auto& tp : m_currentTypeParams) { + if (tp.name == name) { + if (tp.bound.className.empty() && tp.bound.value == ValueType::Unknown && + tp.bound.typeArgs.empty()) + return std::nullopt; + return tp.bound; } - return std::nullopt; } + return std::nullopt; +} - SemanticAnalyser::MethodInfo* SemanticAnalyser::findMethodInHierarchy( - const TypeInfo& classType, const std::string& method, - const std::vector* params) const { - TypeInfo searchType = classType; - if (classType.isTypeParam) { - auto bound = getTypeParamBound(classType.className); - if (!bound || bound->className.empty()) - return nullptr; - searchType = *bound; - } - const ClassInfo* cur = findClass(searchType.className); - if (!params) { - while (cur) { - auto mit = cur->methods.find(method); - if (mit != cur->methods.end() && !mit->second.empty()) - return const_cast(&mit->second.front()); - if (cur->base.empty()) - break; - cur = findClass(cur->base); - } +SemanticAnalyser::MethodInfo* SemanticAnalyser::findMethodInHierarchy( + const TypeInfo& classType, const std::string& method, + const std::vector* params) const { + TypeInfo searchType = classType; + if (classType.isTypeParam) { + auto bound = getTypeParamBound(classType.className); + if (!bound || bound->className.empty()) return nullptr; - } - - struct Candidate { - MethodInfo* method = nullptr; - int cost = 0; - }; - std::unordered_set hiddenSignatures; - std::vector matches; + searchType = *bound; + } + const ClassInfo* cur = findClass(searchType.className); + if (!params) { while (cur) { auto mit = cur->methods.find(method); - if (mit != cur->methods.end()) { - for (auto& cand : mit->second) { - auto expected = - substituteMany(cand.paramTypes, cur->typeParams, searchType.typeArgs); - std::string signature = methodSignatureLabel(cand.name, expected); - if (hiddenSignatures.count(signature)) - continue; - hiddenSignatures.insert(signature); - auto cost = paramsConversionCost(expected, *params); - if (!cost) - continue; - matches.push_back({const_cast(&cand), *cost}); - } - } + if (mit != cur->methods.end() && !mit->second.empty()) + return const_cast(&mit->second.front()); if (cur->base.empty()) break; cur = findClass(cur->base); } - if (matches.empty()) - return nullptr; + return nullptr; + } - int bestCost = std::numeric_limits::max(); - MethodInfo* best = nullptr; - bool ambiguous = false; - for (const auto& candidate : matches) { - if (candidate.cost < bestCost) { - bestCost = candidate.cost; - best = candidate.method; - ambiguous = false; - } else if (candidate.cost == bestCost) { - ambiguous = true; + struct Candidate { + MethodInfo* method = nullptr; + int cost = 0; + }; + std::unordered_set hiddenSignatures; + std::vector matches; + while (cur) { + auto mit = cur->methods.find(method); + if (mit != cur->methods.end()) { + for (auto& cand : mit->second) { + auto expected = + substituteMany(cand.paramTypes, cur->typeParams, searchType.typeArgs); + std::string signature = methodSignatureLabel(cand.name, expected); + if (hiddenSignatures.count(signature)) + continue; + hiddenSignatures.insert(signature); + auto cost = paramsConversionCost(expected, *params); + if (!cost) + continue; + matches.push_back({const_cast(&cand), *cost}); } } - if (ambiguous) - return nullptr; - return best; + if (cur->base.empty()) + break; + cur = findClass(cur->base); } + if (matches.empty()) + return nullptr; - SemanticAnalyser::FieldInfo* SemanticAnalyser::findFieldInHierarchy( - const TypeInfo& classType, const std::string& field) const { - TypeInfo searchType = classType; - if (classType.isTypeParam) { - auto bound = getTypeParamBound(classType.className); - if (!bound || bound->className.empty()) - return nullptr; - searchType = *bound; - } - const ClassInfo* cur = findClass(searchType.className); - while (cur) { - auto fit = cur->fields.find(field); - if (fit != cur->fields.end()) - return const_cast(&fit->second); - if (cur->base.empty()) - break; - cur = findClass(cur->base); + int bestCost = std::numeric_limits::max(); + MethodInfo* best = nullptr; + bool ambiguous = false; + for (const auto& candidate : matches) { + if (candidate.cost < bestCost) { + bestCost = candidate.cost; + best = candidate.method; + ambiguous = false; + } else if (candidate.cost == bestCost) { + ambiguous = true; } - return nullptr; } - - const SemanticAnalyser::FieldInfo* SemanticAnalyser::resolveField(const std::string& name, - int line, int column) const { - if (m_currentClass.empty()) - return nullptr; - TypeInfo curType = combine(ValueType::Unknown, m_currentClass); - FieldInfo* field = findFieldInHierarchy(curType, name); - if (!field) + if (ambiguous) + return nullptr; + return best; +} + +SemanticAnalyser::FieldInfo* SemanticAnalyser::findFieldInHierarchy( + const TypeInfo& classType, const std::string& field) const { + TypeInfo searchType = classType; + if (classType.isTypeParam) { + auto bound = getTypeParamBound(classType.className); + if (!bound || bound->className.empty()) return nullptr; - if (!isAccessible(field->visibility, field->owner, m_currentClass)) { - throw BlochError(ErrorCategory::Semantic, line, column, - "field '" + name + "' is not accessible here"); - } - if (m_inStaticContext && !field->isStatic) { - throw BlochError(ErrorCategory::Semantic, line, column, - "instance field '" + name + - "' cannot be referenced in a static " - "context"); - } - return field; + searchType = *bound; + } + const ClassInfo* cur = findClass(searchType.className); + while (cur) { + auto fit = cur->fields.find(field); + if (fit != cur->fields.end()) + return const_cast(&fit->second); + if (cur->base.empty()) + break; + cur = findClass(cur->base); + } + return nullptr; +} + +const SemanticAnalyser::FieldInfo* SemanticAnalyser::resolveField(const std::string& name, int line, + int column) const { + if (m_currentClass.empty()) + return nullptr; + TypeInfo curType = combine(ValueType::Unknown, m_currentClass); + FieldInfo* field = findFieldInHierarchy(curType, name); + if (!field) + return nullptr; + if (!isAccessible(field->visibility, field->owner, m_currentClass)) { + throw BlochError(ErrorCategory::Semantic, line, column, + "field '" + name + "' is not accessible here"); + } + if (m_inStaticContext && !field->isStatic) { + throw BlochError(ErrorCategory::Semantic, line, column, + "instance field '" + name + + "' cannot be referenced in a static " + "context"); } + return field; +} - bool SemanticAnalyser::isSubclassOf(const std::string& derived, const std::string& base) const { - if (derived.empty() || base.empty()) - return false; - const ClassInfo* cur = findClass(derived); - while (cur) { - if (cur->base == base) - return true; - cur = findClass(cur->base); - } +bool SemanticAnalyser::isSubclassOf(const std::string& derived, const std::string& base) const { + if (derived.empty() || base.empty()) return false; + const ClassInfo* cur = findClass(derived); + while (cur) { + if (cur->base == base) + return true; + cur = findClass(cur->base); } + return false; +} - int SemanticAnalyser::inheritanceDistance(const std::string& derived, - const std::string& base) const { - if (derived.empty() || base.empty()) - return -1; - if (derived == base) - return 0; - int distance = 0; - const ClassInfo* cur = findClass(derived); - while (cur && !cur->base.empty()) { - ++distance; - if (cur->base == base) - return distance; - cur = findClass(cur->base); - } +int SemanticAnalyser::inheritanceDistance(const std::string& derived, + const std::string& base) const { + if (derived.empty() || base.empty()) return -1; + if (derived == base) + return 0; + int distance = 0; + const ClassInfo* cur = findClass(derived); + while (cur && !cur->base.empty()) { + ++distance; + if (cur->base == base) + return distance; + cur = findClass(cur->base); } + return -1; +} - bool SemanticAnalyser::isAssignableType(const TypeInfo& expected, - const TypeInfo& actual) const { - bool expectedIsArray = isArrayType(expected); - bool expectedIsClassRef = isClassRefType(expected); - - if (actual.value == ValueType::Null) { - return expectedIsClassRef; - } +bool SemanticAnalyser::isAssignableType(const TypeInfo& expected, const TypeInfo& actual) const { + bool expectedIsArray = isArrayType(expected); + bool expectedIsClassRef = isClassRefType(expected); - if (expected.className.empty()) { - if (expected.value == ValueType::Unknown || actual.value == ValueType::Unknown) - return true; - if (actual.className.empty()) - return matchesPrimitive(expected.value, actual.value); - return false; - } + if (actual.value == ValueType::Null) { + return expectedIsClassRef; + } - if (expected.isTypeParam) { - if (actual.value != ValueType::Unknown && actual.className.empty()) - return false; // primitives cannot satisfy type params - if (actual.isTypeParam) - return expected.className == actual.className; - if (auto bound = getTypeParamBound(expected.className)) { - if (!bound->className.empty()) - return isAssignableType(*bound, actual); - } + if (expected.className.empty()) { + if (expected.value == ValueType::Unknown || actual.value == ValueType::Unknown) return true; - } + if (actual.className.empty()) + return matchesPrimitive(expected.value, actual.value); + return false; + } - if (expectedIsArray) { - if (!isArrayType(actual)) - return false; - return typeEquals(expected, actual); + if (expected.isTypeParam) { + if (actual.value != ValueType::Unknown && actual.className.empty()) + return false; // primitives cannot satisfy type params + if (actual.isTypeParam) + return expected.className == actual.className; + if (auto bound = getTypeParamBound(expected.className)) { + if (!bound->className.empty()) + return isAssignableType(*bound, actual); } + return true; + } - if (actual.className.empty()) - return actual.value == ValueType::Unknown; - if (actual.isTypeParam) { - auto bound = getTypeParamBound(actual.className); - if (!bound || bound->className.empty()) - return false; - return isAssignableType(expected, *bound); - } + if (expectedIsArray) { + if (!isArrayType(actual)) + return false; + return typeEquals(expected, actual); + } - if (typeEquals(expected, actual)) - return true; + if (actual.className.empty()) + return actual.value == ValueType::Unknown; + if (actual.isTypeParam) { + auto bound = getTypeParamBound(actual.className); + if (!bound || bound->className.empty()) + return false; + return isAssignableType(expected, *bound); + } - if (actual.typeArgs.empty() && expected.typeArgs.empty()) { - return actual.className == expected.className || - isSubclassOf(actual.className, expected.className); - } + if (typeEquals(expected, actual)) + return true; - return false; + if (actual.typeArgs.empty() && expected.typeArgs.empty()) { + return actual.className == expected.className || + isSubclassOf(actual.className, expected.className); } - std::optional SemanticAnalyser::conversionCost(const TypeInfo& expected, - const TypeInfo& actual) const { - if (actual.value == ValueType::Null) { - return isClassRefType(expected) ? std::optional(3) : std::nullopt; - } + return false; +} + +std::optional SemanticAnalyser::conversionCost(const TypeInfo& expected, + const TypeInfo& actual) const { + if (actual.value == ValueType::Null) { + return isClassRefType(expected) ? std::optional(3) : std::nullopt; + } - if (expected.className.empty()) { - if (expected.value == ValueType::Unknown || actual.value == ValueType::Unknown) + if (expected.className.empty()) { + if (expected.value == ValueType::Unknown || actual.value == ValueType::Unknown) + return 0; + if (actual.className.empty()) { + if (expected.value == actual.value) return 0; - if (actual.className.empty()) { - if (expected.value == actual.value) - return 0; - if (expected.value == ValueType::Long && actual.value == ValueType::Int) - return 1; - } - return std::nullopt; + if (expected.value == ValueType::Long && actual.value == ValueType::Int) + return 1; } + return std::nullopt; + } - if (expected.isTypeParam) { - if (actual.value != ValueType::Unknown && actual.className.empty()) - return std::nullopt; - if (actual.isTypeParam) - return expected.className == actual.className ? std::optional(0) - : std::nullopt; - if (auto bound = getTypeParamBound(expected.className)) { - if (!bound->className.empty()) - return conversionCost(*bound, actual); - } - return 1; + if (expected.isTypeParam) { + if (actual.value != ValueType::Unknown && actual.className.empty()) + return std::nullopt; + if (actual.isTypeParam) + return expected.className == actual.className ? std::optional(0) : std::nullopt; + if (auto bound = getTypeParamBound(expected.className)) { + if (!bound->className.empty()) + return conversionCost(*bound, actual); } + return 1; + } - if (isArrayType(expected)) { - if (!isArrayType(actual)) - return std::nullopt; - return typeEquals(expected, actual) ? std::optional(0) : std::nullopt; - } + if (isArrayType(expected)) { + if (!isArrayType(actual)) + return std::nullopt; + return typeEquals(expected, actual) ? std::optional(0) : std::nullopt; + } - if (actual.className.empty()) - return actual.value == ValueType::Unknown ? std::optional(0) : std::nullopt; - if (actual.isTypeParam) { - auto bound = getTypeParamBound(actual.className); - if (!bound || bound->className.empty()) - return std::nullopt; - return conversionCost(expected, *bound); - } + if (actual.className.empty()) + return actual.value == ValueType::Unknown ? std::optional(0) : std::nullopt; + if (actual.isTypeParam) { + auto bound = getTypeParamBound(actual.className); + if (!bound || bound->className.empty()) + return std::nullopt; + return conversionCost(expected, *bound); + } - if (typeEquals(expected, actual)) - return 0; + if (typeEquals(expected, actual)) + return 0; - if (actual.typeArgs.empty() && expected.typeArgs.empty()) { - int distance = inheritanceDistance(actual.className, expected.className); - if (distance >= 0) - return distance; - } + if (actual.typeArgs.empty() && expected.typeArgs.empty()) { + int distance = inheritanceDistance(actual.className, expected.className); + if (distance >= 0) + return distance; + } + return std::nullopt; +} + +std::optional SemanticAnalyser::paramsConversionCost( + const std::vector& expected, const std::vector& actual) const { + if (expected.size() != actual.size()) return std::nullopt; - } - std::optional SemanticAnalyser::paramsConversionCost( - const std::vector& expected, const std::vector& actual) const { - if (expected.size() != actual.size()) + int total = 0; + for (size_t i = 0; i < expected.size(); ++i) { + auto cost = conversionCost(expected[i], actual[i]); + if (!cost) return std::nullopt; - - int total = 0; - for (size_t i = 0; i < expected.size(); ++i) { - auto cost = conversionCost(expected[i], actual[i]); - if (!cost) - return std::nullopt; - total += *cost; - } - return total; + total += *cost; } + return total; +} - bool SemanticAnalyser::paramsAssignable(const std::vector& expected, - const std::vector& actual) const { - return paramsConversionCost(expected, actual).has_value(); - } +bool SemanticAnalyser::paramsAssignable(const std::vector& expected, + const std::vector& actual) const { + return paramsConversionCost(expected, actual).has_value(); +} - void SemanticAnalyser::validateOverrides(ClassInfo& info) { - if (info.base.empty()) { - for (auto& kv : info.methods) { - for (auto& m : kv.second) { - if (m.isOverride) { - throw BlochError(ErrorCategory::Semantic, m.line, m.column, - "'" + m.name + "' marked override but class has no base"); - } - if (m.isStatic && m.isVirtual) { - throw BlochError(ErrorCategory::Semantic, m.line, m.column, - "static method '" + m.name + "' cannot be virtual"); - } - } - } - return; - } +void SemanticAnalyser::validateOverrides(ClassInfo& info) { + if (info.base.empty()) { for (auto& kv : info.methods) { for (auto& m : kv.second) { - if (m.isStatic && (m.isVirtual || m.isOverride)) { - throw BlochError( - ErrorCategory::Semantic, m.line, m.column, - "static method '" + m.name + "' cannot be declared virtual or override"); - } - const MethodInfo* baseMethod = findMethodInHierarchy( - combine(ValueType::Unknown, info.base), m.name, &m.paramTypes); if (m.isOverride) { - if (!baseMethod) { - throw BlochError( - ErrorCategory::Semantic, m.line, m.column, - "'" + m.name + "' marked override but base method not found"); - } - if (!baseMethod->isVirtual) { - throw BlochError(ErrorCategory::Semantic, m.line, m.column, - "'" + m.name + "' overrides a non-virtual base method"); - } - if (baseMethod->isStatic) { - throw BlochError(ErrorCategory::Semantic, m.line, m.column, - "'" + m.name + "' cannot override a static base method"); - } - if (!paramTypesEqual(baseMethod->paramTypes, m.paramTypes)) { - throw BlochError(ErrorCategory::Semantic, m.line, m.column, - "parameter mismatch overriding '" + m.name + "'"); - } - if (!typeEquals(baseMethod->returnType, m.returnType)) { - throw BlochError(ErrorCategory::Semantic, m.line, m.column, - "return type mismatch overriding '" + m.name + "'"); - } + throw BlochError(ErrorCategory::Semantic, m.line, m.column, + "'" + m.name + "' marked override but class has no base"); } - if (m.isVirtual && m.isStatic) { + if (m.isStatic && m.isVirtual) { throw BlochError(ErrorCategory::Semantic, m.line, m.column, "static method '" + m.name + "' cannot be virtual"); } } } + return; } - - void SemanticAnalyser::validateAbstractness(ClassInfo& info) { - std::vector required; - if (!info.base.empty()) { - const ClassInfo* base = findClass(info.base); - if (base) - required.insert(required.end(), base->abstractMethods.begin(), - base->abstractMethods.end()); - } - for (auto& kv : info.methods) { - for (auto& m : kv.second) { - if (m.isVirtual && !m.hasBody) { - required.push_back(m.signature); + for (auto& kv : info.methods) { + for (auto& m : kv.second) { + if (m.isStatic && (m.isVirtual || m.isOverride)) { + throw BlochError( + ErrorCategory::Semantic, m.line, m.column, + "static method '" + m.name + "' cannot be declared virtual or override"); + } + const MethodInfo* baseMethod = findMethodInHierarchy( + combine(ValueType::Unknown, info.base), m.name, &m.paramTypes); + if (m.isOverride) { + if (!baseMethod) { + throw BlochError(ErrorCategory::Semantic, m.line, m.column, + "'" + m.name + "' marked override but base method not found"); } - if (m.hasBody) { - auto it = std::find(required.begin(), required.end(), m.signature); - if (it != required.end()) { - const MethodInfo* baseMethod = findMethodInHierarchy( - combine(ValueType::Unknown, info.base), m.name, &m.paramTypes); - if (baseMethod) { - if (m.isStatic) { - throw BlochError(ErrorCategory::Semantic, m.line, m.column, - "static method '" + m.name + - "' cannot implement abstract base method"); - } - if (!paramTypesEqual(m.paramTypes, baseMethod->paramTypes) || - !typeEquals(baseMethod->returnType, m.returnType)) { - throw BlochError(ErrorCategory::Semantic, m.line, m.column, - "implementation of abstract method '" + m.name + - "' has incompatible signature"); - } + if (!baseMethod->isVirtual) { + throw BlochError(ErrorCategory::Semantic, m.line, m.column, + "'" + m.name + "' overrides a non-virtual base method"); + } + if (baseMethod->isStatic) { + throw BlochError(ErrorCategory::Semantic, m.line, m.column, + "'" + m.name + "' cannot override a static base method"); + } + if (!paramTypesEqual(baseMethod->paramTypes, m.paramTypes)) { + throw BlochError(ErrorCategory::Semantic, m.line, m.column, + "parameter mismatch overriding '" + m.name + "'"); + } + if (!typeEquals(baseMethod->returnType, m.returnType)) { + throw BlochError(ErrorCategory::Semantic, m.line, m.column, + "return type mismatch overriding '" + m.name + "'"); + } + } + if (m.isVirtual && m.isStatic) { + throw BlochError(ErrorCategory::Semantic, m.line, m.column, + "static method '" + m.name + "' cannot be virtual"); + } + } + } +} + +void SemanticAnalyser::validateAbstractness(ClassInfo& info) { + std::vector required; + if (!info.base.empty()) { + const ClassInfo* base = findClass(info.base); + if (base) + required.insert(required.end(), base->abstractMethods.begin(), + base->abstractMethods.end()); + } + for (auto& kv : info.methods) { + for (auto& m : kv.second) { + if (m.isVirtual && !m.hasBody) { + required.push_back(m.signature); + } + if (m.hasBody) { + auto it = std::find(required.begin(), required.end(), m.signature); + if (it != required.end()) { + const MethodInfo* baseMethod = findMethodInHierarchy( + combine(ValueType::Unknown, info.base), m.name, &m.paramTypes); + if (baseMethod) { + if (m.isStatic) { + throw BlochError(ErrorCategory::Semantic, m.line, m.column, + "static method '" + m.name + + "' cannot implement abstract base method"); + } + if (!paramTypesEqual(m.paramTypes, baseMethod->paramTypes) || + !typeEquals(baseMethod->returnType, m.returnType)) { + throw BlochError(ErrorCategory::Semantic, m.line, m.column, + "implementation of abstract method '" + m.name + + "' has incompatible signature"); } - required.erase(it); } + required.erase(it); } } } - info.abstractMethods = required; - if (!info.abstractMethods.empty()) - info.isAbstract = true; } + info.abstractMethods = required; + if (!info.abstractMethods.empty()) + info.isAbstract = true; +} - bool SemanticAnalyser::isAccessible(Visibility visibility, const std::string& owner, - const std::string& accessor) const { - switch (visibility) { - case Visibility::Public: - return true; - case Visibility::Private: - return owner == accessor; - case Visibility::Protected: - return !accessor.empty() && (accessor == owner || isSubclassOf(accessor, owner)); - default: - return false; - } +bool SemanticAnalyser::isAccessible(Visibility visibility, const std::string& owner, + const std::string& accessor) const { + switch (visibility) { + case Visibility::Public: + return true; + case Visibility::Private: + return owner == accessor; + case Visibility::Protected: + return !accessor.empty() && (accessor == owner || isSubclassOf(accessor, owner)); + default: + return false; } +} - bool SemanticAnalyser::isTypeReference(Expression* expr) const { - if (auto var = dynamic_cast(expr)) { - return m_symbols.isTypeName(var->name); - } - return false; +bool SemanticAnalyser::isTypeReference(Expression* expr) const { + if (auto var = dynamic_cast(expr)) { + return m_symbols.isTypeName(var->name); } + return false; +} - bool SemanticAnalyser::isThisReference(Expression* expr) const { - if (dynamic_cast(expr)) - return true; - if (auto var = dynamic_cast(expr)) - return var->name == "this"; +bool SemanticAnalyser::isThisReference(Expression* expr) const { + if (dynamic_cast(expr)) + return true; + if (auto var = dynamic_cast(expr)) + return var->name == "this"; + return false; +} + +bool SemanticAnalyser::isSuperConstructorCall(Statement* stmt) const { + auto exprStmt = dynamic_cast(stmt); + if (!exprStmt) return false; - } + auto call = dynamic_cast(exprStmt->expression.get()); + if (!call) + return false; + return dynamic_cast(call->callee.get()) != nullptr; +} - bool SemanticAnalyser::isSuperConstructorCall(Statement* stmt) const { - auto exprStmt = dynamic_cast(stmt); - if (!exprStmt) - return false; - auto call = dynamic_cast(exprStmt->expression.get()); - if (!call) - return false; - return dynamic_cast(call->callee.get()) != nullptr; +std::unique_ptr SemanticAnalyser::typeFromTypeInfo(const TypeInfo& typeInfo) const { + if (typeInfo.isTypeParam) { + auto named = std::make_unique(std::vector{typeInfo.className}); + return named; } - - std::unique_ptr SemanticAnalyser::typeFromTypeInfo(const TypeInfo& typeInfo) const { - if (typeInfo.isTypeParam) { - auto named = std::make_unique(std::vector{typeInfo.className}); - return named; - } - if (isArrayType(typeInfo) && !typeInfo.typeArgs.empty()) { - auto elementType = typeFromTypeInfo(typeInfo.typeArgs.front()); - if (!elementType) - return nullptr; - return std::make_unique(std::move(elementType)); - } - if (!typeInfo.className.empty()) { - auto named = std::make_unique(std::vector{typeInfo.className}); - for (const auto& arg : typeInfo.typeArgs) { - auto argType = typeFromTypeInfo(arg); - if (!argType) - return nullptr; - named->typeArguments.push_back(std::move(argType)); - } - return named; - } - switch (typeInfo.value) { - case ValueType::Int: - return std::make_unique("int"); - case ValueType::Long: - return std::make_unique("long"); - case ValueType::Float: - return std::make_unique("float"); - case ValueType::Bit: - return std::make_unique("bit"); - case ValueType::Boolean: - return std::make_unique("boolean"); - case ValueType::String: - return std::make_unique("string"); - case ValueType::Char: - return std::make_unique("char"); - case ValueType::Qubit: - return std::make_unique("qubit"); - case ValueType::Void: - return std::make_unique(); - default: + if (isArrayType(typeInfo) && !typeInfo.typeArgs.empty()) { + auto elementType = typeFromTypeInfo(typeInfo.typeArgs.front()); + if (!elementType) + return nullptr; + return std::make_unique(std::move(elementType)); + } + if (!typeInfo.className.empty()) { + auto named = std::make_unique(std::vector{typeInfo.className}); + for (const auto& arg : typeInfo.typeArgs) { + auto argType = typeFromTypeInfo(arg); + if (!argType) return nullptr; + named->typeArguments.push_back(std::move(argType)); + } + return named; + } + switch (typeInfo.value) { + case ValueType::Int: + return std::make_unique("int"); + case ValueType::Long: + return std::make_unique("long"); + case ValueType::Float: + return std::make_unique("float"); + case ValueType::Bit: + return std::make_unique("bit"); + case ValueType::Boolean: + return std::make_unique("boolean"); + case ValueType::String: + return std::make_unique("string"); + case ValueType::Char: + return std::make_unique("char"); + case ValueType::Qubit: + return std::make_unique("qubit"); + case ValueType::Void: + return std::make_unique(); + default: + return nullptr; + } +} + +void SemanticAnalyser::inferDiamondTypeArguments(Expression* initializer, + const TypeInfo& expectedType, int line, + int column) { + auto* newExpr = dynamic_cast(initializer); + if (!newExpr) + return; + auto* named = dynamic_cast(newExpr->classType.get()); + if (!named || !named->hasTypeArgumentList || !named->typeArguments.empty() || + named->nameParts.empty()) + return; + + const std::string& className = named->nameParts.back(); + const ClassInfo* info = findClass(className); + if (!info) + return; + if (info->typeParams.empty()) { + throw BlochError(ErrorCategory::Semantic, line, column, + "type '" + className + "' is not generic"); + } + if (expectedType.className.empty() || expectedType.className != className || + expectedType.typeArgs.empty()) { + throw BlochError( + ErrorCategory::Semantic, line, column, + "cannot infer type arguments for '" + className + "' from assignment target"); + } + if (info->typeParams.size() != expectedType.typeArgs.size()) { + throw BlochError( + ErrorCategory::Semantic, line, column, + "cannot infer type arguments for '" + className + "' from assignment target"); + } + + for (const auto& typeArg : expectedType.typeArgs) { + auto inferred = typeFromTypeInfo(typeArg); + if (!inferred) { + throw BlochError(ErrorCategory::Semantic, line, column, + "cannot infer type arguments for '" + className + "'"); } + named->typeArguments.push_back(std::move(inferred)); } +} - void SemanticAnalyser::inferDiamondTypeArguments(Expression* initializer, - const TypeInfo& expectedType, int line, - int column) { - auto* newExpr = dynamic_cast(initializer); - if (!newExpr) - return; - auto* named = dynamic_cast(newExpr->classType.get()); - if (!named || !named->hasTypeArgumentList || !named->typeArguments.empty() || - named->nameParts.empty()) - return; +void SemanticAnalyser::validateTypedInitializer(const std::string& name, Type* declaredType, + Expression* initializer, int line, int column) { + if (!declaredType || !initializer) + return; - const std::string& className = named->nameParts.back(); - const ClassInfo* info = findClass(className); - if (!info) - return; - if (info->typeParams.empty()) { - throw BlochError(ErrorCategory::Semantic, line, column, - "type '" + className + "' is not generic"); - } - if (expectedType.className.empty() || expectedType.className != className || - expectedType.typeArgs.empty()) { - throw BlochError( - ErrorCategory::Semantic, line, column, - "cannot infer type arguments for '" + className + "' from assignment target"); - } - if (info->typeParams.size() != expectedType.typeArgs.size()) { - throw BlochError( - ErrorCategory::Semantic, line, column, - "cannot infer type arguments for '" + className + "' from assignment target"); - } + TypeInfo targetInfo = typeFromAst(declaredType); + inferDiamondTypeArguments(initializer, targetInfo, line, column); + TypeInfo initInfo = inferTypeInfo(initializer); - for (const auto& typeArg : expectedType.typeArgs) { - auto inferred = typeFromTypeInfo(typeArg); - if (!inferred) { + if (auto arr = dynamic_cast(declaredType)) { + if (auto elem = dynamic_cast(arr->elementType.get())) { + if (elem->name == "qubit") { throw BlochError(ErrorCategory::Semantic, line, column, - "cannot infer type arguments for '" + className + "'"); + "qubit[] cannot be initialised"); } - named->typeArguments.push_back(std::move(inferred)); } - } - - void SemanticAnalyser::validateTypedInitializer(const std::string& name, Type* declaredType, - Expression* initializer, int line, int column) { - if (!declaredType || !initializer) - return; - - TypeInfo targetInfo = typeFromAst(declaredType); - inferDiamondTypeArguments(initializer, targetInfo, line, column); - TypeInfo initInfo = inferTypeInfo(initializer); - - if (auto arr = dynamic_cast(declaredType)) { - if (auto elem = dynamic_cast(arr->elementType.get())) { - if (elem->name == "qubit") { - throw BlochError(ErrorCategory::Semantic, line, column, - "qubit[] cannot be initialised"); - } - } - if (initInfo.value == ValueType::Null) { - throw BlochError(ErrorCategory::Semantic, line, column, - "initialiser for '" + name + "' cannot be null"); - } + if (initInfo.value == ValueType::Null) { + throw BlochError(ErrorCategory::Semantic, line, column, + "initialiser for '" + name + "' cannot be null"); } + } - if (auto call = dynamic_cast(initializer)) { - if (auto callee = dynamic_cast(call->callee.get())) { - if (returnsVoid(callee->name)) { - throw BlochError(ErrorCategory::Semantic, line, column, - "cannot assign result of 'void' function"); - } + if (auto call = dynamic_cast(initializer)) { + if (auto callee = dynamic_cast(call->callee.get())) { + if (returnsVoid(callee->name)) { + throw BlochError(ErrorCategory::Semantic, line, column, + "cannot assign result of 'void' function"); } } + } - // Validate initializer expression first so cast errors surface before type checks. - initializer->accept(*this); + // Validate initializer expression first so cast errors surface before type checks. + initializer->accept(*this); - if (auto primType = targetInfo.value; primType != ValueType::Unknown) { - ValueType initT = initInfo.value; - if (!matchesPrimitive(primType, initT)) { - if (primType == ValueType::Bit) { - if (auto lit = dynamic_cast(initializer)) { - if (lit->literalType == "int") { - throw BlochError(ErrorCategory::Semantic, line, column, - "bit literals must be 0b or 1b"); - } - } - } else if (primType == ValueType::Float) { - if (auto lit = dynamic_cast(initializer)) { - if (lit->literalType == "int") { - throw BlochError(ErrorCategory::Semantic, line, column, - "float literals must end with 'f'"); - } + if (auto primType = targetInfo.value; primType != ValueType::Unknown) { + ValueType initT = initInfo.value; + if (!matchesPrimitive(primType, initT)) { + if (primType == ValueType::Bit) { + if (auto lit = dynamic_cast(initializer)) { + if (lit->literalType == "int") { + throw BlochError(ErrorCategory::Semantic, line, column, + "bit literals must be 0b or 1b"); } } - throw BlochError(ErrorCategory::Semantic, line, column, - "initialiser for '" + name + "' expected '" + - typeToString(primType) + "' but got '" + typeToString(initT) + - "'"); - } - } else if (!targetInfo.className.empty()) { - bool targetIsArray = - targetInfo.className.size() >= 2 && - targetInfo.className.rfind("[]") == targetInfo.className.size() - 2; - if (initInfo.value == ValueType::Null) { - if (targetIsArray) { - throw BlochError(ErrorCategory::Semantic, line, column, - "initialiser for '" + name + "' cannot be null"); + } else if (primType == ValueType::Float) { + if (auto lit = dynamic_cast(initializer)) { + if (lit->literalType == "int") { + throw BlochError(ErrorCategory::Semantic, line, column, + "float literals must end with 'f'"); + } } - } else if (!isAssignableType(targetInfo, initInfo) && - initInfo.value != ValueType::Unknown) { - throw BlochError( - ErrorCategory::Semantic, line, column, - "initialiser for '" + name + "' expected '" + typeLabel(targetInfo) + "'"); } - } - } - - void SemanticAnalyser::recordFinalFieldAssignment(const FieldInfo& field, - const std::string& fieldName, int line, - int column) { - if (!field.isFinal) - return; - - bool isConstructorFieldWrite = m_inConstructor && !field.isStatic; - bool allowed = isConstructorFieldWrite && m_constructorFinalAssignmentDepth == 0; - if (!allowed) { - if (isConstructorFieldWrite && m_constructorFinalAssignmentDepth > 0) { + throw BlochError(ErrorCategory::Semantic, line, column, + "initialiser for '" + name + "' expected '" + typeToString(primType) + + "' but got '" + typeToString(initT) + "'"); + } + } else if (!targetInfo.className.empty()) { + bool targetIsArray = targetInfo.className.size() >= 2 && + targetInfo.className.rfind("[]") == targetInfo.className.size() - 2; + if (initInfo.value == ValueType::Null) { + if (targetIsArray) { throw BlochError(ErrorCategory::Semantic, line, column, - "final field '" + fieldName + - "' must be assigned as a top-level constructor statement"); + "initialiser for '" + name + "' cannot be null"); } - throw BlochError(ErrorCategory::Semantic, line, column, - "cannot assign to final field '" + fieldName + "'"); - } - if (field.owner != m_currentClass) { - throw BlochError(ErrorCategory::Semantic, line, column, - "cannot assign inherited final field '" + fieldName + "'"); - } - if (field.hasInitializer) { - throw BlochError( - ErrorCategory::Semantic, line, column, - "cannot reassign final field '" + fieldName + "' with a declaration initialiser"); - } - - std::string key = field.owner + "::" + fieldName; - int& assignmentCount = m_constructorFinalAssignments[key]; - assignmentCount += 1; - if (assignmentCount > 1) { + } else if (!isAssignableType(targetInfo, initInfo) && + initInfo.value != ValueType::Unknown) { throw BlochError( ErrorCategory::Semantic, line, column, - "final field '" + fieldName + "' may only be assigned once in a constructor"); + "initialiser for '" + name + "' expected '" + typeLabel(targetInfo) + "'"); } } +} - void SemanticAnalyser::buildClassRegistry(Program& program) { - m_classes.clear(); - m_inClassRegistryBuild = true; +void SemanticAnalyser::recordFinalFieldAssignment(const FieldInfo& field, + const std::string& fieldName, int line, + int column) { + if (!field.isFinal) + return; - bool hasExplicitObjectClass = false; - for (const auto& clsNode : program.classes) { - if (clsNode && clsNode->name == "Object") { - hasExplicitObjectClass = true; - break; - } - } - if (!hasExplicitObjectClass) { - ClassInfo rootObject; - rootObject.name = "Object"; - rootObject.line = 0; - rootObject.column = 0; - rootObject.isStatic = false; - rootObject.isAbstract = false; - MethodInfo ctorInfo; - ctorInfo.visibility = Visibility::Public; - ctorInfo.hasBody = true; - ctorInfo.isDefault = true; - ctorInfo.owner = rootObject.name; - ctorInfo.returnType = combine(ValueType::Unknown, rootObject.name); - rootObject.constructors.push_back(std::move(ctorInfo)); - m_classes[rootObject.name] = std::move(rootObject); - } - - for (auto& clsNode : program.classes) { - if (!clsNode) - continue; - if (m_classes.count(clsNode->name)) { - throw BlochError(ErrorCategory::Semantic, clsNode->line, clsNode->column, - "class '" + clsNode->name + "' already declared"); - } - ClassInfo info; - info.name = clsNode->name; - info.line = clsNode->line; - info.column = clsNode->column; - info.isStatic = clsNode->isStatic; - info.isAbstract = clsNode->isAbstract; - - // A base can refer to this class's type parameters: Child extends Base. - m_currentTypeParams.clear(); - for (auto& tp : clsNode->typeParameters) { - ClassInfo::TypeParamInfo pi; - pi.name = tp->name; - if (tp->bound) - pi.bound = typeFromAst(tp->bound.get()); - m_currentTypeParams.push_back(pi); - info.typeParams.push_back(pi); - } - bool hasExplicitBase = false; - if (clsNode->baseType) { - if (auto named = dynamic_cast(clsNode->baseType.get())) { - if (!named->nameParts.empty()) { - info.base = named->nameParts.back(); - info.baseType = typeFromAst(clsNode->baseType.get()); - hasExplicitBase = true; - } - } - } else if (!clsNode->baseName.empty()) { - info.base = clsNode->baseName.back(); - info.baseType = combine(ValueType::Unknown, info.base); - hasExplicitBase = true; - } else if (!info.isStatic && info.name != "Object") { - info.base = "Object"; - info.baseType = combine(ValueType::Unknown, "Object"); - } - if (info.name == "Object") { - if (hasExplicitBase) { - throw BlochError(ErrorCategory::Semantic, info.line, info.column, - "class 'Object' cannot declare a base class"); - } - info.base.clear(); - } - if (info.name == "Object" && !info.typeParams.empty()) { - throw BlochError(ErrorCategory::Semantic, info.line, info.column, - "class 'Object' cannot declare type parameters"); - } - for (auto& member : clsNode->members) { - if (!member) - continue; - if (auto field = dynamic_cast(member.get())) { - if (info.fields.count(field->name)) { - throw BlochError( - ErrorCategory::Semantic, field->line, field->column, - "duplicate field '" + field->name + "' in class '" + info.name + "'"); - } - if (info.isStatic && !field->isStatic) { - throw BlochError( - ErrorCategory::Semantic, field->line, field->column, - "static class '" + info.name + "' cannot declare instance fields"); - } - if (field->isFinal && field->isStatic && !field->initializer) { - throw BlochError( - ErrorCategory::Semantic, field->line, field->column, - "final static field '" + field->name + "' must be initialised"); - } - FieldInfo f; - f.visibility = field->visibility; - f.isStatic = field->isStatic; - f.isFinal = field->isFinal; - f.hasInitializer = field->initializer != nullptr; - f.isTracked = field->isTracked; - f.type = typeFromAst(field->fieldType.get()); - f.owner = info.name; - f.line = field->line; - f.column = field->column; - info.fields[field->name] = f; - } else if (auto method = dynamic_cast(member.get())) { - if (info.isStatic && !method->isStatic) { - throw BlochError( - ErrorCategory::Semantic, method->line, method->column, - "static class '" + info.name + "' cannot declare instance methods"); - } - MethodInfo m; - m.name = method->name; - m.visibility = method->visibility; - m.isStatic = method->isStatic; - m.isVirtual = method->isVirtual; - m.isOverride = method->isOverride; - m.hasBody = method->body != nullptr; - m.returnType = typeFromAst(method->returnType.get()); - m.owner = info.name; - m.line = method->line; - m.column = method->column; - for (auto& p : method->params) - m.paramTypes.push_back(typeFromAst(p->type.get())); - m.signature = methodSignatureLabel(method->name, m.paramTypes); - if (info.methodSignatures.count(m.signature)) { - throw BlochError( - ErrorCategory::Semantic, method->line, method->column, - "duplicate method '" + m.signature + "' in class '" + info.name + "'"); - } - info.methodSignatures.insert(m.signature); - if (m.isStatic && (m.isVirtual || m.isOverride)) { - throw BlochError( - ErrorCategory::Semantic, method->line, method->column, - "static method '" + method->name + "' cannot be virtual or override"); - } - info.methods[method->name].push_back(m); - if (method->isVirtual && !m.hasBody) - info.abstractMethods.push_back(m.signature); - } else if (auto ctor = dynamic_cast(member.get())) { - if (info.isStatic) { - throw BlochError( - ErrorCategory::Semantic, ctor->line, ctor->column, - "static class '" + info.name + "' cannot declare constructors"); - } - MethodInfo ctorInfo; - ctorInfo.visibility = ctor->visibility; - ctorInfo.hasBody = ctor->body != nullptr; - ctorInfo.isDefault = ctor->isDefault; - ctorInfo.owner = info.name; - ctorInfo.line = ctor->line; - ctorInfo.column = ctor->column; - for (auto& p : ctor->params) - ctorInfo.paramTypes.push_back(typeFromAst(p->type.get())); - ctorInfo.returnType = combine(ValueType::Unknown, info.name); - info.constructors.push_back(ctorInfo); - info.ctorDecls.push_back(ctor); - } else if (auto dtor = dynamic_cast(member.get())) { - if (info.isStatic) { - throw BlochError( - ErrorCategory::Semantic, dtor->line, dtor->column, - "static class '" + info.name + "' cannot declare destructors"); - } - if (info.hasUserDestructor) { - throw BlochError( - ErrorCategory::Semantic, dtor->line, dtor->column, - "class '" + info.name + "' cannot declare multiple destructors"); - } - info.hasDestructor = true; - info.hasUserDestructor = true; + bool isConstructorFieldWrite = m_inConstructor && !field.isStatic; + bool allowed = isConstructorFieldWrite && m_constructorFinalAssignmentDepth == 0; + if (!allowed) { + if (isConstructorFieldWrite && m_constructorFinalAssignmentDepth > 0) { + throw BlochError(ErrorCategory::Semantic, line, column, + "final field '" + fieldName + + "' must be assigned as a top-level constructor statement"); + } + throw BlochError(ErrorCategory::Semantic, line, column, + "cannot assign to final field '" + fieldName + "'"); + } + if (field.owner != m_currentClass) { + throw BlochError(ErrorCategory::Semantic, line, column, + "cannot assign inherited final field '" + fieldName + "'"); + } + if (field.hasInitializer) { + throw BlochError( + ErrorCategory::Semantic, line, column, + "cannot reassign final field '" + fieldName + "' with a declaration initialiser"); + } + + std::string key = field.owner + "::" + fieldName; + int& assignmentCount = m_constructorFinalAssignments[key]; + assignmentCount += 1; + if (assignmentCount > 1) { + throw BlochError( + ErrorCategory::Semantic, line, column, + "final field '" + fieldName + "' may only be assigned once in a constructor"); + } +} + +void SemanticAnalyser::buildClassRegistry(Program& program) { + m_classes.clear(); + m_inClassRegistryBuild = true; + + bool hasExplicitObjectClass = false; + for (const auto& clsNode : program.classes) { + if (clsNode && clsNode->name == "Object") { + hasExplicitObjectClass = true; + break; + } + } + if (!hasExplicitObjectClass) { + ClassInfo rootObject; + rootObject.name = "Object"; + rootObject.line = 0; + rootObject.column = 0; + rootObject.isStatic = false; + rootObject.isAbstract = false; + MethodInfo ctorInfo; + ctorInfo.visibility = Visibility::Public; + ctorInfo.hasBody = true; + ctorInfo.isDefault = true; + ctorInfo.owner = rootObject.name; + ctorInfo.returnType = combine(ValueType::Unknown, rootObject.name); + rootObject.constructors.push_back(std::move(ctorInfo)); + m_classes[rootObject.name] = std::move(rootObject); + } + + for (auto& clsNode : program.classes) { + if (!clsNode) + continue; + if (m_classes.count(clsNode->name)) { + throw BlochError(ErrorCategory::Semantic, clsNode->line, clsNode->column, + "class '" + clsNode->name + "' already declared"); + } + ClassInfo info; + info.name = clsNode->name; + info.line = clsNode->line; + info.column = clsNode->column; + info.isStatic = clsNode->isStatic; + info.isAbstract = clsNode->isAbstract; + + // A base can refer to this class's type parameters: Child extends Base. + m_currentTypeParams.clear(); + for (auto& tp : clsNode->typeParameters) { + ClassInfo::TypeParamInfo pi; + pi.name = tp->name; + if (tp->bound) + pi.bound = typeFromAst(tp->bound.get()); + m_currentTypeParams.push_back(pi); + info.typeParams.push_back(pi); + } + bool hasExplicitBase = false; + if (clsNode->baseType) { + if (auto named = dynamic_cast(clsNode->baseType.get())) { + if (!named->nameParts.empty()) { + info.base = named->nameParts.back(); + info.baseType = typeFromAst(clsNode->baseType.get()); + hasExplicitBase = true; } } - if (!info.isStatic && info.constructors.empty()) { + } else if (!clsNode->baseName.empty()) { + info.base = clsNode->baseName.back(); + info.baseType = combine(ValueType::Unknown, info.base); + hasExplicitBase = true; + } else if (!info.isStatic && info.name != "Object") { + info.base = "Object"; + info.baseType = combine(ValueType::Unknown, "Object"); + } + if (info.name == "Object") { + if (hasExplicitBase) { throw BlochError(ErrorCategory::Semantic, info.line, info.column, - "class '" + info.name + "' must declare a constructor"); + "class 'Object' cannot declare a base class"); } - m_classes[info.name] = std::move(info); + info.base.clear(); } - - for (auto& [name, info] : m_classes) { - if (!info.base.empty() && !m_classes.count(info.base)) { - throw BlochError(ErrorCategory::Semantic, 0, 0, - "base class '" + info.base + "' not found for '" + name + "'"); - } + if (info.name == "Object" && !info.typeParams.empty()) { + throw BlochError(ErrorCategory::Semantic, info.line, info.column, + "class 'Object' cannot declare type parameters"); } - - // Extends clauses are converted while forward references are permitted. Now that the - // registry is complete, reject raw generic bases and invalid specialisation bounds. - for (auto& [_, info] : m_classes) { - if (info.base.empty()) + for (auto& member : clsNode->members) { + if (!member) continue; - m_currentTypeParams = info.typeParams; - validateTypeApplication(info.baseType, info.line, info.column); - } - - // Validate default constructors (parameter-field alignment) - for (auto& [name, info] : m_classes) { - for (auto* ctor : info.ctorDecls) { - if (!ctor || !ctor->isDefault) - continue; - for (auto& p : ctor->params) { - auto it = info.fields.find(p->name); - if (it == info.fields.end()) { - throw BlochError(ErrorCategory::Semantic, p->line, p->column, - "default constructor parameter '" + p->name + - "' must match an instance field"); - } - const FieldInfo& f = it->second; - if (f.isStatic) { - throw BlochError(ErrorCategory::Semantic, p->line, p->column, - "default constructor parameter '" + p->name + - "' cannot bind to static field"); - } - if (f.isFinal && f.hasInitializer) { - throw BlochError(ErrorCategory::Semantic, p->line, p->column, - "default constructor cannot bind final field '" + p->name + - "' because it already has a declaration initialiser"); - } - if (f.type.value == ValueType::Qubit || - (!f.type.className.empty() && f.type.value == ValueType::Unknown && - f.type.className == "qubit")) { - throw BlochError(ErrorCategory::Semantic, p->line, p->column, - "default constructor cannot bind qubit fields"); - } - TypeInfo pt = typeFromAst(p->type.get()); - if (!f.type.className.empty()) { - if (pt.className != f.type.className) { - throw BlochError(ErrorCategory::Semantic, p->line, p->column, - "default constructor parameter '" + p->name + - "' must match field type '" + f.type.className + - "'"); - } - } else if (pt.value != f.type.value) { - throw BlochError(ErrorCategory::Semantic, p->line, p->column, - "default constructor parameter '" + p->name + - "' must match field type '" + - typeToString(f.type.value) + "'"); - } + if (auto field = dynamic_cast(member.get())) { + if (info.fields.count(field->name)) { + throw BlochError( + ErrorCategory::Semantic, field->line, field->column, + "duplicate field '" + field->name + "' in class '" + info.name + "'"); } - } - } - - for (auto& [name, info] : m_classes) { - std::unordered_set seen; - const ClassInfo* cur = &info; - while (cur && !cur->base.empty()) { - if (seen.count(cur->base)) { - throw BlochError(ErrorCategory::Semantic, info.line, info.column, - "inheritance cycle involving '" + name + "'"); + if (info.isStatic && !field->isStatic) { + throw BlochError( + ErrorCategory::Semantic, field->line, field->column, + "static class '" + info.name + "' cannot declare instance fields"); } - seen.insert(cur->base); - cur = findClass(cur->base); + if (field->isFinal && field->isStatic && !field->initializer) { + throw BlochError( + ErrorCategory::Semantic, field->line, field->column, + "final static field '" + field->name + "' must be initialised"); + } + FieldInfo f; + f.visibility = field->visibility; + f.isStatic = field->isStatic; + f.isFinal = field->isFinal; + f.hasInitializer = field->initializer != nullptr; + f.isTracked = field->isTracked; + f.type = typeFromAst(field->fieldType.get()); + f.owner = info.name; + f.line = field->line; + f.column = field->column; + info.fields[field->name] = f; + } else if (auto method = dynamic_cast(member.get())) { + if (info.isStatic && !method->isStatic) { + throw BlochError( + ErrorCategory::Semantic, method->line, method->column, + "static class '" + info.name + "' cannot declare instance methods"); + } + MethodInfo m; + m.name = method->name; + m.visibility = method->visibility; + m.isStatic = method->isStatic; + m.isVirtual = method->isVirtual; + m.isOverride = method->isOverride; + m.hasBody = method->body != nullptr; + m.returnType = typeFromAst(method->returnType.get()); + m.owner = info.name; + m.line = method->line; + m.column = method->column; + for (auto& p : method->params) + m.paramTypes.push_back(typeFromAst(p->type.get())); + m.signature = methodSignatureLabel(method->name, m.paramTypes); + if (info.methodSignatures.count(m.signature)) { + throw BlochError( + ErrorCategory::Semantic, method->line, method->column, + "duplicate method '" + m.signature + "' in class '" + info.name + "'"); + } + info.methodSignatures.insert(m.signature); + if (m.isStatic && (m.isVirtual || m.isOverride)) { + throw BlochError( + ErrorCategory::Semantic, method->line, method->column, + "static method '" + method->name + "' cannot be virtual or override"); + } + info.methods[method->name].push_back(m); + if (method->isVirtual && !m.hasBody) + info.abstractMethods.push_back(m.signature); + } else if (auto ctor = dynamic_cast(member.get())) { + if (info.isStatic) { + throw BlochError( + ErrorCategory::Semantic, ctor->line, ctor->column, + "static class '" + info.name + "' cannot declare constructors"); + } + MethodInfo ctorInfo; + ctorInfo.visibility = ctor->visibility; + ctorInfo.hasBody = ctor->body != nullptr; + ctorInfo.isDefault = ctor->isDefault; + ctorInfo.owner = info.name; + ctorInfo.line = ctor->line; + ctorInfo.column = ctor->column; + for (auto& p : ctor->params) + ctorInfo.paramTypes.push_back(typeFromAst(p->type.get())); + ctorInfo.returnType = combine(ValueType::Unknown, info.name); + info.constructors.push_back(ctorInfo); + info.ctorDecls.push_back(ctor); + } else if (auto dtor = dynamic_cast(member.get())) { + if (info.isStatic) { + throw BlochError(ErrorCategory::Semantic, dtor->line, dtor->column, + "static class '" + info.name + "' cannot declare destructors"); + } + if (info.hasUserDestructor) { + throw BlochError( + ErrorCategory::Semantic, dtor->line, dtor->column, + "class '" + info.name + "' cannot declare multiple destructors"); + } + info.hasDestructor = true; + info.hasUserDestructor = true; } } - - std::unordered_set validated; - std::function validateClass = [&](const std::string& name) { - if (validated.count(name)) - return; - auto it = m_classes.find(name); - if (it == m_classes.end()) - return; - if (!it->second.base.empty()) - validateClass(it->second.base); - validateOverrides(it->second); - validateAbstractness(it->second); - validated.insert(name); - }; - for (auto& [name, _] : m_classes) { - validateClass(name); + if (!info.isStatic && info.constructors.empty()) { + throw BlochError(ErrorCategory::Semantic, info.line, info.column, + "class '" + info.name + "' must declare a constructor"); } - m_currentTypeParams.clear(); - m_inClassRegistryBuild = false; - } - - void SemanticAnalyser::beginScope() { - m_symbols.beginScope(); - m_typeStack.emplace_back(); - } - void SemanticAnalyser::endScope() { - m_symbols.endScope(); - if (!m_typeStack.empty()) - m_typeStack.pop_back(); - } - - void SemanticAnalyser::declare(const std::string& name, bool isFinal, const TypeInfo& type, - bool isTypeName) { - m_symbols.declare(name, isFinal, type.value, type.className, isTypeName); - if (!isTypeName && !m_typeStack.empty()) - m_typeStack.back()[name] = type; - } - - bool SemanticAnalyser::isDeclared(const std::string& name) const { - return m_symbols.isDeclared(name); - } - - void SemanticAnalyser::declareFunction(const std::string& name) { m_functions.insert(name); } - - bool SemanticAnalyser::isFunctionDeclared(const std::string& name) const { - return m_functions.count(name) > 0 || builtInGates.count(name) > 0; + m_classes[info.name] = std::move(info); } - bool SemanticAnalyser::isFinal(const std::string& name) const { - return m_symbols.isFinal(name); + for (auto& [name, info] : m_classes) { + if (!info.base.empty() && !m_classes.count(info.base)) { + throw BlochError(ErrorCategory::Semantic, 0, 0, + "base class '" + info.base + "' not found for '" + name + "'"); + } } - size_t SemanticAnalyser::getFunctionParamCount(const std::string& name) const { - auto it = m_functionInfo.find(name); - if (it != m_functionInfo.end()) - return it->second.paramTypes.size(); - auto builtin = builtInGates.find(name); - if (builtin != builtInGates.end()) - return builtin->second.paramTypes.size(); - return 0; + // Extends clauses are converted while forward references are permitted. Now that the + // registry is complete, reject raw generic bases and invalid specialisation bounds. + for (auto& [_, info] : m_classes) { + if (info.base.empty()) + continue; + m_currentTypeParams = info.typeParams; + validateTypeApplication(info.baseType, info.line, info.column); } - std::vector SemanticAnalyser::getFunctionParamTypes( - const std::string& name) const { - auto it = m_functionInfo.find(name); - if (it != m_functionInfo.end()) - return it->second.paramTypes; - auto builtin = builtInGates.find(name); - if (builtin != builtInGates.end()) { - std::vector params; - for (auto v : builtin->second.paramTypes) params.push_back(combine(v, "")); - return params; + // Validate default constructors (parameter-field alignment) + for (auto& [name, info] : m_classes) { + for (auto* ctor : info.ctorDecls) { + if (!ctor || !ctor->isDefault) + continue; + for (auto& p : ctor->params) { + auto it = info.fields.find(p->name); + if (it == info.fields.end()) { + throw BlochError(ErrorCategory::Semantic, p->line, p->column, + "default constructor parameter '" + p->name + + "' must match an instance field"); + } + const FieldInfo& f = it->second; + if (f.isStatic) { + throw BlochError(ErrorCategory::Semantic, p->line, p->column, + "default constructor parameter '" + p->name + + "' cannot bind to static field"); + } + if (f.isFinal && f.hasInitializer) { + throw BlochError(ErrorCategory::Semantic, p->line, p->column, + "default constructor cannot bind final field '" + p->name + + "' because it already has a declaration initialiser"); + } + if (f.type.value == ValueType::Qubit || + (!f.type.className.empty() && f.type.value == ValueType::Unknown && + f.type.className == "qubit")) { + throw BlochError(ErrorCategory::Semantic, p->line, p->column, + "default constructor cannot bind qubit fields"); + } + TypeInfo pt = typeFromAst(p->type.get()); + if (!f.type.className.empty()) { + if (pt.className != f.type.className) { + throw BlochError(ErrorCategory::Semantic, p->line, p->column, + "default constructor parameter '" + p->name + + "' must match field type '" + f.type.className + "'"); + } + } else if (pt.value != f.type.value) { + throw BlochError(ErrorCategory::Semantic, p->line, p->column, + "default constructor parameter '" + p->name + + "' must match field type '" + typeToString(f.type.value) + + "'"); + } + } } - return {}; } - SemanticAnalyser::TypeInfo SemanticAnalyser::getVariableType(const std::string& name) const { - for (auto it = m_typeStack.rbegin(); it != m_typeStack.rend(); ++it) { - auto found = it->find(name); - if (found != it->end()) - return found->second; + for (auto& [name, info] : m_classes) { + std::unordered_set seen; + const ClassInfo* cur = &info; + while (cur && !cur->base.empty()) { + if (seen.count(cur->base)) { + throw BlochError(ErrorCategory::Semantic, info.line, info.column, + "inheritance cycle involving '" + name + "'"); + } + seen.insert(cur->base); + cur = findClass(cur->base); } - return combine(m_symbols.getType(name), m_symbols.getClassName(name)); } - std::string SemanticAnalyser::getVariableClassName(const std::string& name) const { - return m_symbols.getClassName(name); + std::unordered_set validated; + std::function validateClass = [&](const std::string& name) { + if (validated.count(name)) + return; + auto it = m_classes.find(name); + if (it == m_classes.end()) + return; + if (!it->second.base.empty()) + validateClass(it->second.base); + validateOverrides(it->second); + validateAbstractness(it->second); + validated.insert(name); + }; + for (auto& [name, _] : m_classes) { + validateClass(name); + } + m_currentTypeParams.clear(); + m_inClassRegistryBuild = false; +} + +void SemanticAnalyser::beginScope() { + m_symbols.beginScope(); + m_typeStack.emplace_back(); +} +void SemanticAnalyser::endScope() { + m_symbols.endScope(); + if (!m_typeStack.empty()) + m_typeStack.pop_back(); +} + +void SemanticAnalyser::declare(const std::string& name, bool isFinal, const TypeInfo& type, + bool isTypeName) { + m_symbols.declare(name, isFinal, type.value, type.className, isTypeName); + if (!isTypeName && !m_typeStack.empty()) + m_typeStack.back()[name] = type; +} + +bool SemanticAnalyser::isDeclared(const std::string& name) const { + return m_symbols.isDeclared(name); +} + +void SemanticAnalyser::declareFunction(const std::string& name) { m_functions.insert(name); } + +bool SemanticAnalyser::isFunctionDeclared(const std::string& name) const { + return m_functions.count(name) > 0 || builtInGates.count(name) > 0; +} + +bool SemanticAnalyser::isFinal(const std::string& name) const { return m_symbols.isFinal(name); } + +size_t SemanticAnalyser::getFunctionParamCount(const std::string& name) const { + auto it = m_functionInfo.find(name); + if (it != m_functionInfo.end()) + return it->second.paramTypes.size(); + auto builtin = builtInGates.find(name); + if (builtin != builtInGates.end()) + return builtin->second.paramTypes.size(); + return 0; +} + +std::vector SemanticAnalyser::getFunctionParamTypes( + const std::string& name) const { + auto it = m_functionInfo.find(name); + if (it != m_functionInfo.end()) + return it->second.paramTypes; + auto builtin = builtInGates.find(name); + if (builtin != builtInGates.end()) { + std::vector params; + for (auto v : builtin->second.paramTypes) + params.push_back(combine(v, "")); + return params; + } + return {}; +} + +SemanticAnalyser::TypeInfo SemanticAnalyser::getVariableType(const std::string& name) const { + for (auto it = m_typeStack.rbegin(); it != m_typeStack.rend(); ++it) { + auto found = it->find(name); + if (found != it->end()) + return found->second; + } + return combine(m_symbols.getType(name), m_symbols.getClassName(name)); +} + +std::string SemanticAnalyser::getVariableClassName(const std::string& name) const { + return m_symbols.getClassName(name); +} + +bool SemanticAnalyser::returnsVoid(const std::string& name) const { + auto it = m_functionInfo.find(name); + if (it != m_functionInfo.end()) + return it->second.returnType.value == ValueType::Void && + it->second.returnType.className.empty(); + auto builtin = builtInGates.find(name); + if (builtin != builtInGates.end()) + return builtin->second.returnType == ValueType::Void; + return false; +} + +SemanticAnalyser::TypeInfo SemanticAnalyser::inferTypeInfo(Expression* expr) const { + if (!expr) + return combine(ValueType::Unknown, ""); + if (dynamic_cast(expr)) + return combine(ValueType::Null, ""); + if (auto lit = dynamic_cast(expr)) + return combine(typeFromString(lit->literalType), ""); + if (auto var = dynamic_cast(expr)) { + TypeInfo local = getVariableType(var->name); + if (local.value != ValueType::Unknown || !local.className.empty()) + return local; + if (auto field = resolveField(var->name, var->line, var->column)) + return field->type; + // If it's a known type name, treat it as a type reference (e.g., for static calls). + if (m_symbols.isTypeName(var->name)) + return combine(ValueType::Unknown, var->name); + return combine(ValueType::Unknown, ""); } - - bool SemanticAnalyser::returnsVoid(const std::string& name) const { - auto it = m_functionInfo.find(name); - if (it != m_functionInfo.end()) - return it->second.returnType.value == ValueType::Void && - it->second.returnType.className.empty(); - auto builtin = builtInGates.find(name); - if (builtin != builtInGates.end()) - return builtin->second.returnType == ValueType::Void; - return false; + if (dynamic_cast(expr)) + return combine(ValueType::Unknown, m_currentClass); + if (auto par = dynamic_cast(expr)) + return inferTypeInfo(par->expression.get()); + if (auto cast = dynamic_cast(expr)) + return typeFromAst(cast->targetType.get()); + if (dynamic_cast(expr)) + return combine(ValueType::Bit, ""); + if (dynamic_cast(expr)) { + const ClassInfo* cur = findClass(m_currentClass); + if (cur && !cur->base.empty()) + return cur->baseType; + return combine(ValueType::Unknown, ""); } - - SemanticAnalyser::TypeInfo SemanticAnalyser::inferTypeInfo(Expression* expr) const { - if (!expr) - return combine(ValueType::Unknown, ""); - if (dynamic_cast(expr)) - return combine(ValueType::Null, ""); - if (auto lit = dynamic_cast(expr)) - return combine(typeFromString(lit->literalType), ""); - if (auto var = dynamic_cast(expr)) { - TypeInfo local = getVariableType(var->name); - if (local.value != ValueType::Unknown || !local.className.empty()) - return local; - if (auto field = resolveField(var->name, var->line, var->column)) - return field->type; - // If it's a known type name, treat it as a type reference (e.g., for static calls). - if (m_symbols.isTypeName(var->name)) - return combine(ValueType::Unknown, var->name); - return combine(ValueType::Unknown, ""); - } - if (dynamic_cast(expr)) - return combine(ValueType::Unknown, m_currentClass); - if (auto par = dynamic_cast(expr)) - return inferTypeInfo(par->expression.get()); - if (auto cast = dynamic_cast(expr)) - return typeFromAst(cast->targetType.get()); - if (dynamic_cast(expr)) - return combine(ValueType::Bit, ""); - if (dynamic_cast(expr)) { - const ClassInfo* cur = findClass(m_currentClass); - if (cur && !cur->base.empty()) - return cur->baseType; - return combine(ValueType::Unknown, ""); - } - if (auto call = dynamic_cast(expr)) { - std::vector argTypes; - for (auto& a : call->arguments) argTypes.push_back(inferTypeInfo(a.get())); - if (auto callee = dynamic_cast(call->callee.get())) { - auto it = m_functionInfo.find(callee->name); - if (it != m_functionInfo.end()) - return it->second.returnType; - auto bi = builtInGates.find(callee->name); - if (bi != builtInGates.end()) - return combine(bi->second.returnType, ""); - if (!m_currentClass.empty()) { - auto* method = findMethodInHierarchy( - combine(ValueType::Unknown, m_currentClass), callee->name, &argTypes); - if (method) { - if (!method->isStatic && m_inStaticContext) - return combine(ValueType::Unknown, ""); - if (!isAccessible(method->visibility, method->owner, m_currentClass)) - return combine(ValueType::Unknown, ""); - return method->returnType; - } + if (auto call = dynamic_cast(expr)) { + std::vector argTypes; + for (auto& a : call->arguments) + argTypes.push_back(inferTypeInfo(a.get())); + if (auto callee = dynamic_cast(call->callee.get())) { + auto it = m_functionInfo.find(callee->name); + if (it != m_functionInfo.end()) + return it->second.returnType; + auto bi = builtInGates.find(callee->name); + if (bi != builtInGates.end()) + return combine(bi->second.returnType, ""); + if (!m_currentClass.empty()) { + auto* method = findMethodInHierarchy(combine(ValueType::Unknown, m_currentClass), + callee->name, &argTypes); + if (method) { + if (!method->isStatic && m_inStaticContext) + return combine(ValueType::Unknown, ""); + if (!isAccessible(method->visibility, method->owner, m_currentClass)) + return combine(ValueType::Unknown, ""); + return method->returnType; } - } else if (auto mem = dynamic_cast(call->callee.get())) { - auto obj = inferTypeInfo(mem->object.get()); - if (!obj.className.empty()) { - auto* method = findMethodInHierarchy(obj, mem->member, &argTypes); - if (method) { - TypeInfo ret = method->returnType; - const ClassInfo* cls = findClass(obj.className); - if (cls && !cls->typeParams.empty()) { - // First, substitute class-level type arguments directly. - ret = substituteTypeParams(ret, cls->typeParams, obj.typeArgs); - // Infer type arguments from actual call arguments (very simple: map - // type params to the corresponding actual argument types). - std::unordered_map binding; - std::function bindParams; - bindParams = [&](const TypeInfo& expected, const TypeInfo& actual) { - if (expected.isTypeParam) { - binding[expected.className] = actual; - return; - } - for (size_t i = 0; - i < expected.typeArgs.size() && i < actual.typeArgs.size(); - ++i) - bindParams(expected.typeArgs[i], actual.typeArgs[i]); - }; - auto params = method->paramTypes; - for (size_t i = 0; i < params.size() && i < argTypes.size(); ++i) - bindParams(params[i], argTypes[i]); - - std::function subst = - [&](const TypeInfo& t) { - if (t.isTypeParam) { - auto it = binding.find(t.className); - if (it != binding.end()) - return it->second; - } - TypeInfo out = t; - out.typeArgs.clear(); - for (const auto& a : t.typeArgs) - out.typeArgs.push_back(subst(a)); - return out; - }; - ret = subst(ret); - } - return ret; + } + } else if (auto mem = dynamic_cast(call->callee.get())) { + auto obj = inferTypeInfo(mem->object.get()); + if (!obj.className.empty()) { + auto* method = findMethodInHierarchy(obj, mem->member, &argTypes); + if (method) { + TypeInfo ret = method->returnType; + const ClassInfo* cls = findClass(obj.className); + if (cls && !cls->typeParams.empty()) { + // First, substitute class-level type arguments directly. + ret = substituteTypeParams(ret, cls->typeParams, obj.typeArgs); + // Infer type arguments from actual call arguments (very simple: map + // type params to the corresponding actual argument types). + std::unordered_map binding; + std::function bindParams; + bindParams = [&](const TypeInfo& expected, const TypeInfo& actual) { + if (expected.isTypeParam) { + binding[expected.className] = actual; + return; + } + for (size_t i = 0; + i < expected.typeArgs.size() && i < actual.typeArgs.size(); ++i) + bindParams(expected.typeArgs[i], actual.typeArgs[i]); + }; + auto params = method->paramTypes; + for (size_t i = 0; i < params.size() && i < argTypes.size(); ++i) + bindParams(params[i], argTypes[i]); + + std::function subst = [&](const TypeInfo& t) { + if (t.isTypeParam) { + auto it = binding.find(t.className); + if (it != binding.end()) + return it->second; + } + TypeInfo out = t; + out.typeArgs.clear(); + for (const auto& a : t.typeArgs) + out.typeArgs.push_back(subst(a)); + return out; + }; + ret = subst(ret); } + return ret; } } - return combine(ValueType::Unknown, ""); } - if (auto bin = dynamic_cast(expr)) { - auto lt = inferTypeInfo(bin->left.get()); - auto rt = inferTypeInfo(bin->right.get()); - if (bin->op == "==" || bin->op == "!=" || bin->op == "<" || bin->op == ">" || - bin->op == "<=" || bin->op == ">=" || bin->op == "&&" || bin->op == "||") - return combine(ValueType::Boolean, ""); - if (bin->op == "+" && (lt.value == ValueType::String || rt.value == ValueType::String)) - return combine(ValueType::String, ""); - if (bin->op == "+") { - ValueType promoted = numericPromotion(lt.value, rt.value); - if (promoted == ValueType::Unknown) - return combine(ValueType::Unknown, ""); - return combine(promoted == ValueType::Bit ? ValueType::Int : promoted, ""); - } - if (bin->op == "-" || bin->op == "*") { - ValueType promoted = numericPromotion(lt.value, rt.value); - if (promoted == ValueType::Unknown) - return combine(ValueType::Unknown, ""); - return combine(promoted == ValueType::Bit ? ValueType::Int : promoted, ""); - } - if (bin->op == "/") { - return combine(ValueType::Float, ""); - } - if (bin->op == "%") { - ValueType promoted = numericPromotion(lt.value, rt.value); - if (promoted == ValueType::Unknown) - return combine(ValueType::Unknown, ""); - return combine(promoted == ValueType::Long ? ValueType::Long : ValueType::Int, ""); - } - if (bin->op == "&" || bin->op == "|" || bin->op == "^") { - if (lt.value == ValueType::Bit && rt.value == ValueType::Bit) - return combine(ValueType::Bit, ""); - } - return combine(ValueType::Unknown, ""); + return combine(ValueType::Unknown, ""); + } + if (auto bin = dynamic_cast(expr)) { + auto lt = inferTypeInfo(bin->left.get()); + auto rt = inferTypeInfo(bin->right.get()); + if (bin->op == "==" || bin->op == "!=" || bin->op == "<" || bin->op == ">" || + bin->op == "<=" || bin->op == ">=" || bin->op == "&&" || bin->op == "||") + return combine(ValueType::Boolean, ""); + if (bin->op == "+" && (lt.value == ValueType::String || rt.value == ValueType::String)) + return combine(ValueType::String, ""); + if (bin->op == "+") { + ValueType promoted = numericPromotion(lt.value, rt.value); + if (promoted == ValueType::Unknown) + return combine(ValueType::Unknown, ""); + return combine(promoted == ValueType::Bit ? ValueType::Int : promoted, ""); } - if (auto un = dynamic_cast(expr)) { - auto rt = inferTypeInfo(un->right.get()); - if (un->op == "-") { - if (rt.value == ValueType::Float) - return combine(ValueType::Float, ""); - if (rt.value == ValueType::Long) - return combine(ValueType::Long, ""); - return combine(ValueType::Int, ""); - } - if (un->op == "!") - return combine(ValueType::Boolean, ""); - if (un->op == "~") - return combine((rt.value == ValueType::Bit) ? ValueType::Bit : ValueType::Unknown, - ""); - return combine(ValueType::Unknown, ""); + if (bin->op == "-" || bin->op == "*") { + ValueType promoted = numericPromotion(lt.value, rt.value); + if (promoted == ValueType::Unknown) + return combine(ValueType::Unknown, ""); + return combine(promoted == ValueType::Bit ? ValueType::Int : promoted, ""); + } + if (bin->op == "/") { + return combine(ValueType::Float, ""); } - if (auto post = dynamic_cast(expr)) { - if (auto v = dynamic_cast(post->left.get())) { - TypeInfo local = getVariableType(v->name); - if (local.value != ValueType::Unknown || !local.className.empty()) - return local; - if (auto field = resolveField(v->name, v->line, v->column)) - return field->type; + if (bin->op == "%") { + ValueType promoted = numericPromotion(lt.value, rt.value); + if (promoted == ValueType::Unknown) return combine(ValueType::Unknown, ""); - } + return combine(promoted == ValueType::Long ? ValueType::Long : ValueType::Int, ""); + } + if (bin->op == "&" || bin->op == "|" || bin->op == "^") { + if (lt.value == ValueType::Bit && rt.value == ValueType::Bit) + return combine(ValueType::Bit, ""); + } + return combine(ValueType::Unknown, ""); + } + if (auto un = dynamic_cast(expr)) { + auto rt = inferTypeInfo(un->right.get()); + if (un->op == "-") { + if (rt.value == ValueType::Float) + return combine(ValueType::Float, ""); + if (rt.value == ValueType::Long) + return combine(ValueType::Long, ""); + return combine(ValueType::Int, ""); + } + if (un->op == "!") + return combine(ValueType::Boolean, ""); + if (un->op == "~") + return combine((rt.value == ValueType::Bit) ? ValueType::Bit : ValueType::Unknown, ""); + return combine(ValueType::Unknown, ""); + } + if (auto post = dynamic_cast(expr)) { + if (auto v = dynamic_cast(post->left.get())) { + TypeInfo local = getVariableType(v->name); + if (local.value != ValueType::Unknown || !local.className.empty()) + return local; + if (auto field = resolveField(v->name, v->line, v->column)) + return field->type; return combine(ValueType::Unknown, ""); } - if (auto mem = dynamic_cast(expr)) { - auto obj = inferTypeInfo(mem->object.get()); - if (!obj.className.empty()) { - TypeInfo searchType = obj; - if (obj.isTypeParam) { - auto bound = getTypeParamBound(obj.className); - if (bound && !bound->className.empty()) - searchType = *bound; - } - auto* field = findFieldInHierarchy(searchType, mem->member); - if (field) { - if (!searchType.typeArgs.empty()) { - const ClassInfo* ci = findClass(searchType.className); - if (ci) - return substituteTypeParams(field->type, ci->typeParams, - searchType.typeArgs); - } - return field->type; + return combine(ValueType::Unknown, ""); + } + if (auto mem = dynamic_cast(expr)) { + auto obj = inferTypeInfo(mem->object.get()); + if (!obj.className.empty()) { + TypeInfo searchType = obj; + if (obj.isTypeParam) { + auto bound = getTypeParamBound(obj.className); + if (bound && !bound->className.empty()) + searchType = *bound; + } + auto* field = findFieldInHierarchy(searchType, mem->member); + if (field) { + if (!searchType.typeArgs.empty()) { + const ClassInfo* ci = findClass(searchType.className); + if (ci) + return substituteTypeParams(field->type, ci->typeParams, + searchType.typeArgs); } - auto* method = findMethodInHierarchy(searchType, mem->member); - if (method) { - if (!searchType.typeArgs.empty()) { - const ClassInfo* ci = findClass(searchType.className); - if (ci) - return substituteTypeParams(method->returnType, ci->typeParams, - searchType.typeArgs); - } - return method->returnType; + return field->type; + } + auto* method = findMethodInHierarchy(searchType, mem->member); + if (method) { + if (!searchType.typeArgs.empty()) { + const ClassInfo* ci = findClass(searchType.className); + if (ci) + return substituteTypeParams(method->returnType, ci->typeParams, + searchType.typeArgs); } + return method->returnType; } - return combine(ValueType::Unknown, ""); - } - if (auto idx = dynamic_cast(expr)) { - auto collectionType = inferTypeInfo(idx->collection.get()); - if (isArrayType(collectionType) && !collectionType.typeArgs.empty()) - return collectionType.typeArgs.front(); - return combine(ValueType::Unknown, ""); - } - if (auto newExpr = dynamic_cast(expr)) { - return typeFromAst(newExpr->classType.get()); } return combine(ValueType::Unknown, ""); } + if (auto idx = dynamic_cast(expr)) { + auto collectionType = inferTypeInfo(idx->collection.get()); + if (isArrayType(collectionType) && !collectionType.typeArgs.empty()) + return collectionType.typeArgs.front(); + return combine(ValueType::Unknown, ""); + } + if (auto newExpr = dynamic_cast(expr)) { + return typeFromAst(newExpr->classType.get()); + } + return combine(ValueType::Unknown, ""); +} - std::optional SemanticAnalyser::evaluateConstInt(Expression* expr) const { - if (!expr) +std::optional SemanticAnalyser::evaluateConstInt(Expression* expr) const { + if (!expr) + return std::nullopt; + if (auto lit = dynamic_cast(expr)) { + if (lit->literalType != "int") return std::nullopt; - if (auto lit = dynamic_cast(expr)) { - if (lit->literalType != "int") - return std::nullopt; - try { - return std::stoi(lit->value); - } catch (...) { - return std::nullopt; - } - } - if (auto var = dynamic_cast(expr)) { - if (!isDeclared(var->name)) { - throw BlochError(ErrorCategory::Semantic, var->line, var->column, - "Variable '" + var->name + "' not declared"); - } - if (!isFinal(var->name)) - return std::nullopt; - if (m_symbols.getType(var->name) != ValueType::Int) - return std::nullopt; - return m_symbols.getConstInt(var->name); - } - if (auto par = dynamic_cast(expr)) - return evaluateConstInt(par->expression.get()); - if (auto unary = dynamic_cast(expr)) { - if (unary->op == "-") { - auto val = evaluateConstInt(unary->right.get()); - if (val) - return -*val; - } + try { + return std::stoi(lit->value); + } catch (...) { return std::nullopt; } - if (auto cast = dynamic_cast(expr)) { - auto target = typeFromAst(cast->targetType.get()); - if (target.value == ValueType::Int) - return evaluateConstInt(cast->expression.get()); - return std::nullopt; + } + if (auto var = dynamic_cast(expr)) { + if (!isDeclared(var->name)) { + throw BlochError(ErrorCategory::Semantic, var->line, var->column, + "Variable '" + var->name + "' not declared"); } - if (auto bin = dynamic_cast(expr)) { - auto left = evaluateConstInt(bin->left.get()); - auto right = evaluateConstInt(bin->right.get()); - if (!left || !right) - return std::nullopt; - if (bin->op == "+") - return *left + *right; - if (bin->op == "-") - return *left - *right; - if (bin->op == "*") - return *left * *right; - if (bin->op == "/") { - if (*right == 0) - throw BlochError(ErrorCategory::Semantic, bin->line, bin->column, - "division by zero in constant integer expression"); - return *left / *right; - } - if (bin->op == "%") { - if (*right == 0) - throw BlochError(ErrorCategory::Semantic, bin->line, bin->column, - "modulo by zero in constant integer expression"); - return *left % *right; - } + if (!isFinal(var->name)) + return std::nullopt; + if (m_symbols.getType(var->name) != ValueType::Int) return std::nullopt; + return m_symbols.getConstInt(var->name); + } + if (auto par = dynamic_cast(expr)) + return evaluateConstInt(par->expression.get()); + if (auto unary = dynamic_cast(expr)) { + if (unary->op == "-") { + auto val = evaluateConstInt(unary->right.get()); + if (val) + return -*val; } return std::nullopt; } - - void SemanticAnalyser::analyse(Program& program) { - // Reset state so analyser instances are safely reusable after success or failure. - m_symbols = SymbolTable{}; - m_currentReturn = combine(ValueType::Unknown, ""); - m_foundReturn = false; - m_functions.clear(); - m_functionInfo.clear(); - m_classes.clear(); - m_currentClass.clear(); - m_inStaticContext = false; - m_inConstructor = false; - m_inDestructor = false; - m_allowSuperConstructorCall = false; - m_currentMethod.clear(); - m_currentMethodIsOverride = false; - m_typeStack.clear(); - m_currentTypeParams.clear(); - m_inClassRegistryBuild = false; - m_constructorFinalAssignments.clear(); - m_constructorFinalAssignmentDepth = 0; - - buildClassRegistry(program); - ScopeGuard globalScope(*this); - // Make class names visible as types/values (for static access). - for (const auto& kv : m_classes) { - declare(kv.first, true, combine(ValueType::Unknown, kv.first), true); - } - // Predeclare functions - for (auto& fn : program.functions) { - if (isFunctionDeclared(fn->name)) { - throw BlochError(ErrorCategory::Semantic, fn->line, fn->column, - "'" + fn->name + "' is already declared in this scope"); - } - declareFunction(fn->name); - } - for (auto& cls : program.classes) - if (cls) - cls->accept(*this); - for (auto& fn : program.functions) fn->accept(*this); - for (auto& stmt : program.statements) stmt->accept(*this); + if (auto cast = dynamic_cast(expr)) { + auto target = typeFromAst(cast->targetType.get()); + if (target.value == ValueType::Int) + return evaluateConstInt(cast->expression.get()); + return std::nullopt; } - - void SemanticAnalyser::visit(VariableDeclaration& node) { - if (isDeclared(node.name)) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'" + node.name + "' is already declared in this scope"); - } - TypeInfo tinfo = typeFromAst(node.varType.get()); - if (tinfo.value == ValueType::Void) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "variables cannot have type 'void'"); - } - for (const auto& ann : node.annotations) { - if (ann && ann->name == "quantum") { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'@quantum' may annotate functions only"); - } - if (ann && ann->name == "shots") { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'@shots(N)' can only decorate the main() function."); - } - } - declare(node.name, node.isFinal, tinfo); - if (auto arr = dynamic_cast(node.varType.get())) { - bool hasExplicitSize = arr->size >= 0 || arr->sizeExpression != nullptr; - if (arr->sizeExpression) { - auto size = evaluateConstInt(arr->sizeExpression.get()); - if (!size) { - int line = - arr->sizeExpression->line > 0 ? arr->sizeExpression->line : node.line; - int col = - arr->sizeExpression->column > 0 ? arr->sizeExpression->column : node.column; - throw BlochError(ErrorCategory::Semantic, line, col, - "array size must be a compile-time constant 'int' (e.g. a " - "final int)"); - } - arr->size = *size; - hasExplicitSize = true; - } - if (hasExplicitSize && arr->size < 0) { - int line = node.line; - int col = node.column; - if (arr->sizeExpression && arr->sizeExpression->line > 0) { - line = arr->sizeExpression->line; - col = arr->sizeExpression->column; - } - throw BlochError(ErrorCategory::Semantic, line, col, - "array size must be non-negative"); - } - } - if (node.isFinal && !node.initializer) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "final variable '" + node.name + "' must be initialised"); - } - if (node.initializer) - validateTypedInitializer(node.name, node.varType.get(), node.initializer.get(), - node.line, node.column); - if (node.isFinal) { - if (auto prim = dynamic_cast(node.varType.get())) { - if (prim->name == "int" && node.initializer) { - auto val = evaluateConstInt(node.initializer.get()); - if (val) - m_symbols.setConstInt(node.name, *val); - } - } + if (auto bin = dynamic_cast(expr)) { + auto left = evaluateConstInt(bin->left.get()); + auto right = evaluateConstInt(bin->right.get()); + if (!left || !right) + return std::nullopt; + if (bin->op == "+") + return *left + *right; + if (bin->op == "-") + return *left - *right; + if (bin->op == "*") + return *left * *right; + if (bin->op == "/") { + if (*right == 0) + throw BlochError(ErrorCategory::Semantic, bin->line, bin->column, + "division by zero in constant integer expression"); + return *left / *right; + } + if (bin->op == "%") { + if (*right == 0) + throw BlochError(ErrorCategory::Semantic, bin->line, bin->column, + "modulo by zero in constant integer expression"); + return *left % *right; } + return std::nullopt; } - - void SemanticAnalyser::visit(BlockStatement& node) { - bool trackNesting = m_inConstructor; - if (trackNesting) - m_constructorFinalAssignmentDepth += 1; - auto restoreNesting = makeScopeExit([&] { - if (trackNesting) - m_constructorFinalAssignmentDepth -= 1; - }); - ScopeGuard scope(*this); - for (auto& stmt : node.statements) stmt->accept(*this); + return std::nullopt; +} + +void SemanticAnalyser::analyse(Program& program) { + // Reset state so analyser instances are safely reusable after success or failure. + m_symbols = SymbolTable{}; + m_currentReturn = combine(ValueType::Unknown, ""); + m_foundReturn = false; + m_functions.clear(); + m_functionInfo.clear(); + m_classes.clear(); + m_currentClass.clear(); + m_inStaticContext = false; + m_inConstructor = false; + m_inDestructor = false; + m_allowSuperConstructorCall = false; + m_currentMethod.clear(); + m_currentMethodIsOverride = false; + m_typeStack.clear(); + m_currentTypeParams.clear(); + m_inClassRegistryBuild = false; + m_constructorFinalAssignments.clear(); + m_constructorFinalAssignmentDepth = 0; + + buildClassRegistry(program); + ScopeGuard globalScope(*this); + // Make class names visible as types/values (for static access). + for (const auto& kv : m_classes) { + declare(kv.first, true, combine(ValueType::Unknown, kv.first), true); + } + // Predeclare functions + for (auto& fn : program.functions) { + if (isFunctionDeclared(fn->name)) { + throw BlochError(ErrorCategory::Semantic, fn->line, fn->column, + "'" + fn->name + "' is already declared in this scope"); + } + declareFunction(fn->name); + } + for (auto& cls : program.classes) + if (cls) + cls->accept(*this); + for (auto& fn : program.functions) + fn->accept(*this); + for (auto& stmt : program.statements) + stmt->accept(*this); +} + +void SemanticAnalyser::visit(VariableDeclaration& node) { + if (isDeclared(node.name)) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "'" + node.name + "' is already declared in this scope"); } - - void SemanticAnalyser::visit(ExpressionStatement& node) { - if (node.expression) - node.expression->accept(*this); + TypeInfo tinfo = typeFromAst(node.varType.get()); + if (tinfo.value == ValueType::Void) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "variables cannot have type 'void'"); } - - void SemanticAnalyser::visit(ReturnStatement& node) { - m_foundReturn = true; - bool isVoid = - (m_currentReturn.value == ValueType::Void && m_currentReturn.className.empty()); - if (node.value && isVoid) { + for (const auto& ann : node.annotations) { + if (ann && ann->name == "quantum") { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "void function cannot return a value"); + "'@quantum' may annotate functions only"); } - if (!node.value && !isVoid) { + if (ann && ann->name == "shots") { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "Non-void function must return a value"); - } - if (node.value) { - inferDiamondTypeArguments(node.value.get(), m_currentReturn, node.line, node.column); - auto actual = inferTypeInfo(node.value.get()); - if (!isVoid) { - bool expectedIsArray = - m_currentReturn.className.size() >= 2 && - m_currentReturn.className.rfind("[]") == m_currentReturn.className.size() - 2; - if (actual.value == ValueType::Null) { - if (m_currentReturn.className.empty() || expectedIsArray) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "return type mismatch"); - } - } else if (!m_currentReturn.className.empty()) { - if (!isAssignableType(m_currentReturn, actual)) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "return type mismatch"); - } - } else if (!matchesPrimitive(m_currentReturn.value, actual.value)) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "return type mismatch"); - } - } - node.value->accept(*this); - } - } - - void SemanticAnalyser::visit(IfStatement& node) { - bool trackNesting = m_inConstructor; - if (trackNesting) - m_constructorFinalAssignmentDepth += 1; - auto restoreNesting = makeScopeExit([&] { - if (trackNesting) - m_constructorFinalAssignmentDepth -= 1; - }); - if (node.condition) { - node.condition->accept(*this); - auto condType = inferTypeInfo(node.condition.get()); - if (!isBooleanLike(condType)) { - int line = node.condition->line > 0 ? node.condition->line : node.line; - int col = node.condition->column > 0 ? node.condition->column : node.column; + "'@shots(N)' can only decorate the main() function."); + } + } + declare(node.name, node.isFinal, tinfo); + if (auto arr = dynamic_cast(node.varType.get())) { + bool hasExplicitSize = arr->size >= 0 || arr->sizeExpression != nullptr; + if (arr->sizeExpression) { + auto size = evaluateConstInt(arr->sizeExpression.get()); + if (!size) { + int line = arr->sizeExpression->line > 0 ? arr->sizeExpression->line : node.line; + int col = + arr->sizeExpression->column > 0 ? arr->sizeExpression->column : node.column; throw BlochError(ErrorCategory::Semantic, line, col, - "if condition must be 'boolean' or 'bit'"); + "array size must be a compile-time constant 'int' (e.g. a " + "final int)"); + } + arr->size = *size; + hasExplicitSize = true; + } + if (hasExplicitSize && arr->size < 0) { + int line = node.line; + int col = node.column; + if (arr->sizeExpression && arr->sizeExpression->line > 0) { + line = arr->sizeExpression->line; + col = arr->sizeExpression->column; } + throw BlochError(ErrorCategory::Semantic, line, col, "array size must be non-negative"); } - if (node.thenBranch) - node.thenBranch->accept(*this); - if (node.elseBranch) - node.elseBranch->accept(*this); } - - void SemanticAnalyser::visit(TernaryStatement& node) { - bool trackNesting = m_inConstructor; - if (trackNesting) - m_constructorFinalAssignmentDepth += 1; - auto restoreNesting = makeScopeExit([&] { - if (trackNesting) - m_constructorFinalAssignmentDepth -= 1; - }); - if (node.condition) { - node.condition->accept(*this); - auto condType = inferTypeInfo(node.condition.get()); - if (!isBooleanLike(condType)) { - int line = node.condition->line > 0 ? node.condition->line : node.line; - int col = node.condition->column > 0 ? node.condition->column : node.column; - throw BlochError(ErrorCategory::Semantic, line, col, - "conditional statement requires 'boolean' or 'bit' condition"); + if (node.isFinal && !node.initializer) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "final variable '" + node.name + "' must be initialised"); + } + if (node.initializer) + validateTypedInitializer(node.name, node.varType.get(), node.initializer.get(), node.line, + node.column); + if (node.isFinal) { + if (auto prim = dynamic_cast(node.varType.get())) { + if (prim->name == "int" && node.initializer) { + auto val = evaluateConstInt(node.initializer.get()); + if (val) + m_symbols.setConstInt(node.name, *val); } } - if (node.thenBranch) - node.thenBranch->accept(*this); - if (node.elseBranch) - node.elseBranch->accept(*this); } +} - void SemanticAnalyser::visit(ForStatement& node) { - bool trackNesting = m_inConstructor; +void SemanticAnalyser::visit(BlockStatement& node) { + bool trackNesting = m_inConstructor; + if (trackNesting) + m_constructorFinalAssignmentDepth += 1; + auto restoreNesting = makeScopeExit([&] { if (trackNesting) - m_constructorFinalAssignmentDepth += 1; - auto restoreNesting = makeScopeExit([&] { - if (trackNesting) - m_constructorFinalAssignmentDepth -= 1; - }); - ScopeGuard scope(*this); - if (node.initializer) - node.initializer->accept(*this); - if (node.condition) { - node.condition->accept(*this); - auto condType = inferTypeInfo(node.condition.get()); - if (!isBooleanLike(condType)) { - int line = node.condition->line > 0 ? node.condition->line : node.line; - int col = node.condition->column > 0 ? node.condition->column : node.column; - throw BlochError(ErrorCategory::Semantic, line, col, - "for-loop condition must be 'boolean' or 'bit'"); + m_constructorFinalAssignmentDepth -= 1; + }); + ScopeGuard scope(*this); + for (auto& stmt : node.statements) + stmt->accept(*this); +} + +void SemanticAnalyser::visit(ExpressionStatement& node) { + if (node.expression) + node.expression->accept(*this); +} + +void SemanticAnalyser::visit(ReturnStatement& node) { + m_foundReturn = true; + bool isVoid = (m_currentReturn.value == ValueType::Void && m_currentReturn.className.empty()); + if (node.value && isVoid) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "void function cannot return a value"); + } + if (!node.value && !isVoid) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "Non-void function must return a value"); + } + if (node.value) { + inferDiamondTypeArguments(node.value.get(), m_currentReturn, node.line, node.column); + auto actual = inferTypeInfo(node.value.get()); + if (!isVoid) { + bool expectedIsArray = + m_currentReturn.className.size() >= 2 && + m_currentReturn.className.rfind("[]") == m_currentReturn.className.size() - 2; + if (actual.value == ValueType::Null) { + if (m_currentReturn.className.empty() || expectedIsArray) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "return type mismatch"); + } + } else if (!m_currentReturn.className.empty()) { + if (!isAssignableType(m_currentReturn, actual)) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "return type mismatch"); + } + } else if (!matchesPrimitive(m_currentReturn.value, actual.value)) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "return type mismatch"); } } - if (node.increment) - node.increment->accept(*this); - if (node.body) - node.body->accept(*this); + node.value->accept(*this); } +} - void SemanticAnalyser::visit(WhileStatement& node) { - bool trackNesting = m_inConstructor; +void SemanticAnalyser::visit(IfStatement& node) { + bool trackNesting = m_inConstructor; + if (trackNesting) + m_constructorFinalAssignmentDepth += 1; + auto restoreNesting = makeScopeExit([&] { if (trackNesting) - m_constructorFinalAssignmentDepth += 1; - auto restoreNesting = makeScopeExit([&] { - if (trackNesting) - m_constructorFinalAssignmentDepth -= 1; - }); - if (node.condition) { - node.condition->accept(*this); - auto condType = inferTypeInfo(node.condition.get()); - if (!isBooleanLike(condType)) { - int line = node.condition->line > 0 ? node.condition->line : node.line; - int col = node.condition->column > 0 ? node.condition->column : node.column; - throw BlochError(ErrorCategory::Semantic, line, col, - "while condition must be 'boolean' or 'bit'"); - } - } - if (node.body) - node.body->accept(*this); + m_constructorFinalAssignmentDepth -= 1; + }); + if (node.condition) { + node.condition->accept(*this); + auto condType = inferTypeInfo(node.condition.get()); + if (!isBooleanLike(condType)) { + int line = node.condition->line > 0 ? node.condition->line : node.line; + int col = node.condition->column > 0 ? node.condition->column : node.column; + throw BlochError(ErrorCategory::Semantic, line, col, + "if condition must be 'boolean' or 'bit'"); + } + } + if (node.thenBranch) + node.thenBranch->accept(*this); + if (node.elseBranch) + node.elseBranch->accept(*this); +} + +void SemanticAnalyser::visit(TernaryStatement& node) { + bool trackNesting = m_inConstructor; + if (trackNesting) + m_constructorFinalAssignmentDepth += 1; + auto restoreNesting = makeScopeExit([&] { + if (trackNesting) + m_constructorFinalAssignmentDepth -= 1; + }); + if (node.condition) { + node.condition->accept(*this); + auto condType = inferTypeInfo(node.condition.get()); + if (!isBooleanLike(condType)) { + int line = node.condition->line > 0 ? node.condition->line : node.line; + int col = node.condition->column > 0 ? node.condition->column : node.column; + throw BlochError(ErrorCategory::Semantic, line, col, + "conditional statement requires 'boolean' or 'bit' condition"); + } + } + if (node.thenBranch) + node.thenBranch->accept(*this); + if (node.elseBranch) + node.elseBranch->accept(*this); +} + +void SemanticAnalyser::visit(ForStatement& node) { + bool trackNesting = m_inConstructor; + if (trackNesting) + m_constructorFinalAssignmentDepth += 1; + auto restoreNesting = makeScopeExit([&] { + if (trackNesting) + m_constructorFinalAssignmentDepth -= 1; + }); + ScopeGuard scope(*this); + if (node.initializer) + node.initializer->accept(*this); + if (node.condition) { + node.condition->accept(*this); + auto condType = inferTypeInfo(node.condition.get()); + if (!isBooleanLike(condType)) { + int line = node.condition->line > 0 ? node.condition->line : node.line; + int col = node.condition->column > 0 ? node.condition->column : node.column; + throw BlochError(ErrorCategory::Semantic, line, col, + "for-loop condition must be 'boolean' or 'bit'"); + } + } + if (node.increment) + node.increment->accept(*this); + if (node.body) + node.body->accept(*this); +} + +void SemanticAnalyser::visit(WhileStatement& node) { + bool trackNesting = m_inConstructor; + if (trackNesting) + m_constructorFinalAssignmentDepth += 1; + auto restoreNesting = makeScopeExit([&] { + if (trackNesting) + m_constructorFinalAssignmentDepth -= 1; + }); + if (node.condition) { + node.condition->accept(*this); + auto condType = inferTypeInfo(node.condition.get()); + if (!isBooleanLike(condType)) { + int line = node.condition->line > 0 ? node.condition->line : node.line; + int col = node.condition->column > 0 ? node.condition->column : node.column; + throw BlochError(ErrorCategory::Semantic, line, col, + "while condition must be 'boolean' or 'bit'"); + } + } + if (node.body) + node.body->accept(*this); +} + +void SemanticAnalyser::visit(EchoStatement& node) { + if (node.value) + node.value->accept(*this); +} + +void SemanticAnalyser::visit(ResetStatement& node) { + if (node.target) + node.target->accept(*this); + auto tinfo = inferTypeInfo(node.target.get()); + if (tinfo.value != ValueType::Unknown && tinfo.value != ValueType::Qubit) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "reset target must be a 'qubit'"); } +} - void SemanticAnalyser::visit(EchoStatement& node) { - if (node.value) - node.value->accept(*this); +void SemanticAnalyser::visit(MeasureStatement& node) { + if (node.qubit) + node.qubit->accept(*this); + auto tinfo = inferTypeInfo(node.qubit.get()); + bool isQubitArray = (!tinfo.className.empty() && tinfo.className == "qubit[]"); + bool isQubit = tinfo.value == ValueType::Qubit; + if (tinfo.value != ValueType::Unknown && !isQubit && !isQubitArray) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "measure target must be a 'qubit' or 'qubit[]'"); } +} - void SemanticAnalyser::visit(ResetStatement& node) { - if (node.target) - node.target->accept(*this); - auto tinfo = inferTypeInfo(node.target.get()); - if (tinfo.value != ValueType::Unknown && tinfo.value != ValueType::Qubit) { +void SemanticAnalyser::visit(DestroyStatement& node) { + if (node.target) { + auto t = inferTypeInfo(node.target.get()); + if (t.className.empty() && t.value != ValueType::Null) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "reset target must be a 'qubit'"); + "'destroy' requires a class reference"); } + node.target->accept(*this); } +} - void SemanticAnalyser::visit(MeasureStatement& node) { - if (node.qubit) - node.qubit->accept(*this); - auto tinfo = inferTypeInfo(node.qubit.get()); - bool isQubitArray = (!tinfo.className.empty() && tinfo.className == "qubit[]"); - bool isQubit = tinfo.value == ValueType::Qubit; - if (tinfo.value != ValueType::Unknown && !isQubit && !isQubitArray) { +void SemanticAnalyser::visit(AssignmentStatement& node) { + if (isDeclared(node.name)) { + if (isFinal(node.name)) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "measure target must be a 'qubit' or 'qubit[]'"); - } - } - - void SemanticAnalyser::visit(DestroyStatement& node) { - if (node.target) { - auto t = inferTypeInfo(node.target.get()); - if (t.className.empty() && t.value != ValueType::Null) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'destroy' requires a class reference"); - } - node.target->accept(*this); - } - } - - void SemanticAnalyser::visit(AssignmentStatement& node) { - if (isDeclared(node.name)) { - if (isFinal(node.name)) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "Cannot assign to final variable '" + node.name + "'"); - } - if (node.value) { - TypeInfo targetType = getVariableType(node.name); - inferDiamondTypeArguments(node.value.get(), targetType, node.line, node.column); - auto valType = inferTypeInfo(node.value.get()); - if (valType.value == ValueType::Null) { - bool targetIsArray = - targetType.className.size() >= 2 && - targetType.className.rfind("[]") == targetType.className.size() - 2; - bool targetIsClass = !targetType.className.empty() && !targetIsArray; - if (!targetIsClass) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "cannot assign null to '" + node.name + "'"); - } - } else if (valType.value != ValueType::Unknown && - !isAssignableType(targetType, valType)) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "assignment to '" + node.name + "' expects '" + - typeLabel(targetType) + "'"); - } - node.value->accept(*this); - } - return; + "Cannot assign to final variable '" + node.name + "'"); } - if (auto field = resolveField(node.name, node.line, node.column)) { - recordFinalFieldAssignment(*field, node.name, node.line, node.column); - if (node.value) { - TypeInfo targetType = field->type; - inferDiamondTypeArguments(node.value.get(), targetType, node.line, node.column); - auto valType = inferTypeInfo(node.value.get()); - bool fieldIsArray = + if (node.value) { + TypeInfo targetType = getVariableType(node.name); + inferDiamondTypeArguments(node.value.get(), targetType, node.line, node.column); + auto valType = inferTypeInfo(node.value.get()); + if (valType.value == ValueType::Null) { + bool targetIsArray = targetType.className.size() >= 2 && targetType.className.rfind("[]") == targetType.className.size() - 2; - if (valType.value == ValueType::Null) { - if (fieldIsArray || targetType.className.empty()) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "cannot assign null to field '" + node.name + "'"); - } - } - if (!targetType.className.empty() && valType.value != ValueType::Null && - valType.value != ValueType::Unknown && !isAssignableType(targetType, valType)) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "assignment to field '" + node.name + "' expects '" + - typeLabel(targetType) + "'"); - } else if (field->type.value != ValueType::Unknown && - valType.value != ValueType::Unknown && - !matchesPrimitive(targetType.value, valType.value)) { + bool targetIsClass = !targetType.className.empty() && !targetIsArray; + if (!targetIsClass) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "assignment to field '" + node.name + "' expects '" + - typeToString(targetType.value) + "'"); + "cannot assign null to '" + node.name + "'"); } - node.value->accept(*this); + } else if (valType.value != ValueType::Unknown && + !isAssignableType(targetType, valType)) { + throw BlochError( + ErrorCategory::Semantic, node.line, node.column, + "assignment to '" + node.name + "' expects '" + typeLabel(targetType) + "'"); } - return; + node.value->accept(*this); } - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "Variable '" + node.name + "' not declared"); - } - - void SemanticAnalyser::visit(BinaryExpression& node) { - if (node.left) - node.left->accept(*this); - if (node.right) - node.right->accept(*this); - auto lt = inferTypeInfo(node.left.get()); - auto rt = inferTypeInfo(node.right.get()); - auto isStringType = [](const TypeInfo& t) { - return t.className.empty() && t.value == ValueType::String; - }; - auto isBitType = [](const TypeInfo& t) { - return t.className.empty() && t.value == ValueType::Bit; - }; - auto errorWithTypes = [&](const std::string& message) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, message); - }; - if ((lt.value == ValueType::Null || rt.value == ValueType::Null) && node.op != "==" && - node.op != "!=") { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "null can only be used in equality comparisons"); - } - if (node.op == "==" || node.op == "!=") { - bool leftNull = lt.value == ValueType::Null; - bool rightNull = rt.value == ValueType::Null; - if (leftNull && rightNull) - return; - if (leftNull || rightNull) { - const TypeInfo& other = leftNull ? rt : lt; - if (!isClassRefType(other)) { + return; + } + if (auto field = resolveField(node.name, node.line, node.column)) { + recordFinalFieldAssignment(*field, node.name, node.line, node.column); + if (node.value) { + TypeInfo targetType = field->type; + inferDiamondTypeArguments(node.value.get(), targetType, node.line, node.column); + auto valType = inferTypeInfo(node.value.get()); + bool fieldIsArray = targetType.className.size() >= 2 && + targetType.className.rfind("[]") == targetType.className.size() - 2; + if (valType.value == ValueType::Null) { + if (fieldIsArray || targetType.className.empty()) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "null comparison requires a class reference"); - } - return; - } - if (isClassRefType(lt) || isClassRefType(rt)) { - if (!(isClassRefType(lt) && isClassRefType(rt))) { - errorWithTypes("equality on references requires two class references"); + "cannot assign null to field '" + node.name + "'"); } - return; - } - if (isArrayType(lt) || isArrayType(rt)) { - errorWithTypes("equality on arrays is not supported"); } - bool lBool = isBooleanLike(lt); - bool rBool = isBooleanLike(rt); - if (lBool || rBool) { - if (!(lBool && rBool)) { - errorWithTypes( - "equality requires boolean or bit operands when used with " - "boolean/bit"); - } - return; + if (!targetType.className.empty() && valType.value != ValueType::Null && + valType.value != ValueType::Unknown && !isAssignableType(targetType, valType)) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "assignment to field '" + node.name + "' expects '" + + typeLabel(targetType) + "'"); + } else if (field->type.value != ValueType::Unknown && + valType.value != ValueType::Unknown && + !matchesPrimitive(targetType.value, valType.value)) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "assignment to field '" + node.name + "' expects '" + + typeToString(targetType.value) + "'"); } - if (isNumericType(lt) && isNumericType(rt)) - return; - if (lt.className.empty() && rt.className.empty() && lt.value == rt.value && - (lt.value == ValueType::String || lt.value == ValueType::Char)) { - return; + node.value->accept(*this); + } + return; + } + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "Variable '" + node.name + "' not declared"); +} + +void SemanticAnalyser::visit(BinaryExpression& node) { + if (node.left) + node.left->accept(*this); + if (node.right) + node.right->accept(*this); + auto lt = inferTypeInfo(node.left.get()); + auto rt = inferTypeInfo(node.right.get()); + auto isStringType = [](const TypeInfo& t) { + return t.className.empty() && t.value == ValueType::String; + }; + auto isBitType = [](const TypeInfo& t) { + return t.className.empty() && t.value == ValueType::Bit; + }; + auto errorWithTypes = [&](const std::string& message) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, message); + }; + if ((lt.value == ValueType::Null || rt.value == ValueType::Null) && node.op != "==" && + node.op != "!=") { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "null can only be used in equality comparisons"); + } + if (node.op == "==" || node.op == "!=") { + bool leftNull = lt.value == ValueType::Null; + bool rightNull = rt.value == ValueType::Null; + if (leftNull && rightNull) + return; + if (leftNull || rightNull) { + const TypeInfo& other = leftNull ? rt : lt; + if (!isClassRefType(other)) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "null comparison requires a class reference"); } - errorWithTypes("operator '" + node.op + "' not supported for types '" + typeLabel(lt) + - "' and '" + typeLabel(rt) + "'"); + return; } - - if (node.op == "&&" || node.op == "||") { - if (!(isBooleanLike(lt) && isBooleanLike(rt))) { - errorWithTypes("logical operator '" + node.op + - "' requires boolean or bit operands"); + if (isClassRefType(lt) || isClassRefType(rt)) { + if (!(isClassRefType(lt) && isClassRefType(rt))) { + errorWithTypes("equality on references requires two class references"); } return; } - - if (node.op == "&" || node.op == "|" || node.op == "^") { - bool lBit = isBitType(lt); - bool rBit = isBitType(rt); - bool lBitArr = isBitArrayType(lt); - bool rBitArr = isBitArrayType(rt); - if (!((lBit || lBitArr) && (rBit || rBitArr))) { - errorWithTypes("bitwise operator '" + node.op + "' requires bit or bit[] operands"); + if (isArrayType(lt) || isArrayType(rt)) { + errorWithTypes("equality on arrays is not supported"); + } + bool lBool = isBooleanLike(lt); + bool rBool = isBooleanLike(rt); + if (lBool || rBool) { + if (!(lBool && rBool)) { + errorWithTypes( + "equality requires boolean or bit operands when used with " + "boolean/bit"); } return; } - - if (node.op == "+" && (isStringType(lt) || isStringType(rt))) + if (isNumericType(lt) && isNumericType(rt)) return; - - if (node.op == "+" || node.op == "-" || node.op == "*" || node.op == "/") { - if (!(isNumericType(lt) && isNumericType(rt))) { - errorWithTypes("operator '" + node.op + - "' requires numeric operands (int, long, float)"); - } + if (lt.className.empty() && rt.className.empty() && lt.value == rt.value && + (lt.value == ValueType::String || lt.value == ValueType::Char)) { return; } + errorWithTypes("operator '" + node.op + "' not supported for types '" + typeLabel(lt) + + "' and '" + typeLabel(rt) + "'"); + } - if (node.op == "%") { - if (!(isNumericType(lt) && isNumericType(rt)) || lt.value == ValueType::Float || - rt.value == ValueType::Float) { - errorWithTypes("operator '%' requires integer operands (int, long)"); - } - return; + if (node.op == "&&" || node.op == "||") { + if (!(isBooleanLike(lt) && isBooleanLike(rt))) { + errorWithTypes("logical operator '" + node.op + "' requires boolean or bit operands"); } + return; + } - if (node.op == "<" || node.op == ">" || node.op == "<=" || node.op == ">=") { - if (!(isNumericType(lt) && isNumericType(rt))) { - errorWithTypes("operator '" + node.op + - "' requires numeric operands (int, long, float)"); - } - return; + if (node.op == "&" || node.op == "|" || node.op == "^") { + bool lBit = isBitType(lt); + bool rBit = isBitType(rt); + bool lBitArr = isBitArrayType(lt); + bool rBitArr = isBitArrayType(rt); + if (!((lBit || lBitArr) && (rBit || rBitArr))) { + errorWithTypes("bitwise operator '" + node.op + "' requires bit or bit[] operands"); } + return; } - void SemanticAnalyser::visit(UnaryExpression& node) { - if (node.right) - node.right->accept(*this); - auto rt = inferTypeInfo(node.right.get()); - if (node.op == "!") { - if (!isBooleanLike(rt)) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "logical '!' requires boolean or bit operand"); - } - return; + if (node.op == "+" && (isStringType(lt) || isStringType(rt))) + return; + + if (node.op == "+" || node.op == "-" || node.op == "*" || node.op == "/") { + if (!(isNumericType(lt) && isNumericType(rt))) { + errorWithTypes("operator '" + node.op + + "' requires numeric operands (int, long, float)"); } - if (node.op == "-") { - if (!isNumericType(rt)) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "unary '-' requires numeric operand (int, long, float)"); - } - return; + return; + } + + if (node.op == "%") { + if (!(isNumericType(lt) && isNumericType(rt)) || lt.value == ValueType::Float || + rt.value == ValueType::Float) { + errorWithTypes("operator '%' requires integer operands (int, long)"); } - if (node.op == "~") { - if (!(rt.className.empty() && rt.value == ValueType::Bit) && !isBitArrayType(rt)) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "bitwise '~' requires bit or bit[] operand"); - } - return; + return; + } + + if (node.op == "<" || node.op == ">" || node.op == "<=" || node.op == ">=") { + if (!(isNumericType(lt) && isNumericType(rt))) { + errorWithTypes("operator '" + node.op + + "' requires numeric operands (int, long, float)"); } + return; } +} - void SemanticAnalyser::visit(CastExpression& node) { - TypeInfo target = typeFromAst(node.targetType.get()); - auto source = inferTypeInfo(node.expression.get()); - auto isNumericNonChar = [](ValueType v) { - return v == ValueType::Int || v == ValueType::Long || v == ValueType::Float || - v == ValueType::Bit; - }; - auto typeLabel = [](const TypeInfo& t) { - if (!t.className.empty()) - return t.className; - return typeToString(t.value); - }; - auto reject = [&](const TypeInfo& from, const TypeInfo& to) { - throw BlochError( - ErrorCategory::Semantic, node.line, node.column, - "Cannot explicitally cast from " + typeLabel(from) + " to " + typeLabel(to)); - }; - if (target.value == ValueType::Void || !target.className.empty() || - !isNumericNonChar(target.value)) { - reject(source, target); +void SemanticAnalyser::visit(UnaryExpression& node) { + if (node.right) + node.right->accept(*this); + auto rt = inferTypeInfo(node.right.get()); + if (node.op == "!") { + if (!isBooleanLike(rt)) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "logical '!' requires boolean or bit operand"); } - if (source.value != ValueType::Unknown) { - if (!isNumericNonChar(source.value) || !source.className.empty()) { - reject(source, target); - } + return; + } + if (node.op == "-") { + if (!isNumericType(rt)) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "unary '-' requires numeric operand (int, long, float)"); } - if (node.expression) - node.expression->accept(*this); + return; } - - void SemanticAnalyser::visit(PostfixExpression& node) { - if (auto var = dynamic_cast(node.left.get())) { - if (isDeclared(var->name)) { - if (isFinal(var->name)) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "Cannot modify final variable '" + var->name + "'"); - } - TypeInfo t = getVariableType(var->name); - if ((t.value != ValueType::Int && t.value != ValueType::Long) || - !t.className.empty()) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "Postfix operator '" + node.op + - "' requires variable of type 'int' or 'long'"); - } - return; - } - if (auto field = resolveField(var->name, node.line, node.column)) { - if (field->isFinal) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "Cannot modify final field '" + var->name + "'"); - } - if (field->type.value != ValueType::Int && field->type.value != ValueType::Long) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "Postfix operator '" + node.op + - "' requires variable of type 'int' or 'long'"); - } - return; - } + if (node.op == "~") { + if (!(rt.className.empty() && rt.value == ValueType::Bit) && !isBitArrayType(rt)) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "Variable '" + var->name + "' not declared"); - } else if (node.left) { - node.left->accept(*this); - throw BlochError( - ErrorCategory::Semantic, node.line, node.column, - "Postfix operator '" + node.op + "' can only be applied to a variable"); + "bitwise '~' requires bit or bit[] operand"); } + return; } +} - void SemanticAnalyser::visit(LiteralExpression&) {} - void SemanticAnalyser::visit(NullLiteralExpression&) {} - - void SemanticAnalyser::visit(VariableExpression& node) { - if (isDeclared(node.name) || isFunctionDeclared(node.name)) - return; - if (resolveField(node.name, node.line, node.column)) - return; - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "Variable '" + node.name + "' not declared"); +void SemanticAnalyser::visit(CastExpression& node) { + TypeInfo target = typeFromAst(node.targetType.get()); + auto source = inferTypeInfo(node.expression.get()); + auto isNumericNonChar = [](ValueType v) { + return v == ValueType::Int || v == ValueType::Long || v == ValueType::Float || + v == ValueType::Bit; + }; + auto typeLabel = [](const TypeInfo& t) { + if (!t.className.empty()) + return t.className; + return typeToString(t.value); + }; + auto reject = [&](const TypeInfo& from, const TypeInfo& to) { + throw BlochError( + ErrorCategory::Semantic, node.line, node.column, + "Cannot explicitally cast from " + typeLabel(from) + " to " + typeLabel(to)); + }; + if (target.value == ValueType::Void || !target.className.empty() || + !isNumericNonChar(target.value)) { + reject(source, target); + } + if (source.value != ValueType::Unknown) { + if (!isNumericNonChar(source.value) || !source.className.empty()) { + reject(source, target); + } } + if (node.expression) + node.expression->accept(*this); +} - void SemanticAnalyser::visit(CallExpression& node) { - std::vector actualTypes; - actualTypes.reserve(node.arguments.size()); - for (auto& arg : node.arguments) actualTypes.push_back(inferTypeInfo(arg.get())); - - auto checkArgs = [&](const std::vector& params, const std::string& name, int line, - int column) { - if (params.size() != node.arguments.size()) { +void SemanticAnalyser::visit(PostfixExpression& node) { + if (auto var = dynamic_cast(node.left.get())) { + if (isDeclared(var->name)) { + if (isFinal(var->name)) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "Cannot modify final variable '" + var->name + "'"); + } + TypeInfo t = getVariableType(var->name); + if ((t.value != ValueType::Int && t.value != ValueType::Long) || !t.className.empty()) { + throw BlochError( + ErrorCategory::Semantic, node.line, node.column, + "Postfix operator '" + node.op + "' requires variable of type 'int' or 'long'"); + } + return; + } + if (auto field = resolveField(var->name, node.line, node.column)) { + if (field->isFinal) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "Cannot modify final field '" + var->name + "'"); + } + if (field->type.value != ValueType::Int && field->type.value != ValueType::Long) { throw BlochError( - ErrorCategory::Semantic, line, column, - "'" + name + "' expects " + std::to_string(params.size()) + " argument(s)"); + ErrorCategory::Semantic, node.line, node.column, + "Postfix operator '" + node.op + "' requires variable of type 'int' or 'long'"); } - for (size_t i = 0; i < node.arguments.size(); ++i) { - auto expected = params[i]; - auto& arg = node.arguments[i]; - auto actual = actualTypes[i]; - bool expectedIsArray = - expected.className.size() >= 2 && - expected.className.rfind("[]") == expected.className.size() - 2; - if (!expected.className.empty()) { - if (expectedIsArray && actual.value == ValueType::Null) { + return; + } + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "Variable '" + var->name + "' not declared"); + } else if (node.left) { + node.left->accept(*this); + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "Postfix operator '" + node.op + "' can only be applied to a variable"); + } +} + +void SemanticAnalyser::visit(LiteralExpression&) {} +void SemanticAnalyser::visit(NullLiteralExpression&) {} + +void SemanticAnalyser::visit(VariableExpression& node) { + if (isDeclared(node.name) || isFunctionDeclared(node.name)) + return; + if (resolveField(node.name, node.line, node.column)) + return; + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "Variable '" + node.name + "' not declared"); +} + +void SemanticAnalyser::visit(CallExpression& node) { + std::vector actualTypes; + actualTypes.reserve(node.arguments.size()); + for (auto& arg : node.arguments) + actualTypes.push_back(inferTypeInfo(arg.get())); + + auto checkArgs = [&](const std::vector& params, const std::string& name, int line, + int column) { + if (params.size() != node.arguments.size()) { + throw BlochError( + ErrorCategory::Semantic, line, column, + "'" + name + "' expects " + std::to_string(params.size()) + " argument(s)"); + } + for (size_t i = 0; i < node.arguments.size(); ++i) { + auto expected = params[i]; + auto& arg = node.arguments[i]; + auto actual = actualTypes[i]; + bool expectedIsArray = expected.className.size() >= 2 && + expected.className.rfind("[]") == expected.className.size() - 2; + if (!expected.className.empty()) { + if (expectedIsArray && actual.value == ValueType::Null) { + throw BlochError(ErrorCategory::Semantic, arg->line, arg->column, + "argument #" + std::to_string(i + 1) + " to '" + name + + "' expected '" + expected.className + "'"); + } + if (expected.isTypeParam) { + if (actual.value != ValueType::Unknown && actual.className.empty()) { throw BlochError(ErrorCategory::Semantic, arg->line, arg->column, "argument #" + std::to_string(i + 1) + " to '" + name + - "' expected '" + expected.className + "'"); + "' expected type parameter '" + expected.className + + "'"); + } + if (actual.isTypeParam) { + // Passing a type parameter to another type-parameter-typed parameter + // is always allowed; bound checking happens when the enclosing type is + // instantiated. + continue; } - if (expected.isTypeParam) { - if (actual.value != ValueType::Unknown && actual.className.empty()) { + if (auto bound = getTypeParamBound(expected.className)) { + if (!bound->className.empty() && !actual.className.empty() && + actual.className != bound->className && + !isSubclassOf(actual.className, bound->className)) { throw BlochError(ErrorCategory::Semantic, arg->line, arg->column, "argument #" + std::to_string(i + 1) + " to '" + name + - "' expected type parameter '" + - expected.className + "'"); - } - if (actual.isTypeParam) { - // Passing a type parameter to another type-parameter-typed parameter - // is always allowed; bound checking happens when the enclosing type is - // instantiated. - continue; - } - if (auto bound = getTypeParamBound(expected.className)) { - if (!bound->className.empty() && !actual.className.empty() && - actual.className != bound->className && - !isSubclassOf(actual.className, bound->className)) { - throw BlochError(ErrorCategory::Semantic, arg->line, arg->column, - "argument #" + std::to_string(i + 1) + " to '" + - name + "' must satisfy bound '" + - typeLabel(*bound) + "'"); - } + "' must satisfy bound '" + typeLabel(*bound) + + "'"); } - continue; - } - if (actual.value == ValueType::Null) - continue; // nullable class refs - if (actual.className.empty()) { - if (actual.value == ValueType::Unknown) - continue; - throw BlochError(ErrorCategory::Semantic, arg->line, arg->column, - "argument #" + std::to_string(i + 1) + " to '" + name + - "' expected '" + typeLabel(expected) + "'"); - } - if (!isAssignableType(expected, actual)) { - throw BlochError(ErrorCategory::Semantic, arg->line, arg->column, - "argument #" + std::to_string(i + 1) + " to '" + name + - "' expected '" + typeLabel(expected) + "'"); } - } else if (expected.value != ValueType::Unknown && - actual.value != ValueType::Unknown && - !matchesPrimitive(expected.value, actual.value)) { + continue; + } + if (actual.value == ValueType::Null) + continue; // nullable class refs + if (actual.className.empty()) { + if (actual.value == ValueType::Unknown) + continue; throw BlochError(ErrorCategory::Semantic, arg->line, arg->column, "argument #" + std::to_string(i + 1) + " to '" + name + - "' expected '" + typeToString(expected.value) + "'"); + "' expected '" + typeLabel(expected) + "'"); } - } - }; - - if (auto var = dynamic_cast(node.callee.get())) { - MethodInfo* methodInfo = nullptr; - if (!isDeclared(var->name) && !isFunctionDeclared(var->name)) { - if (!m_currentClass.empty()) - methodInfo = findMethodInHierarchy(combine(ValueType::Unknown, m_currentClass), - var->name, &actualTypes); - if (methodInfo) { - if (!isAccessible(methodInfo->visibility, methodInfo->owner, m_currentClass)) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "method '" + var->name + "' is not accessible here"); - } - if (!methodInfo->isStatic && m_inStaticContext) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "instance method '" + var->name + - "' cannot be called in a static context"); - } - } else { - if (resolveField(var->name, var->line, var->column)) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'" + var->name + "' is a field and cannot be called"); - } - throw BlochError(ErrorCategory::Semantic, var->line, var->column, - "Variable '" + var->name + "' not declared"); + if (!isAssignableType(expected, actual)) { + throw BlochError(ErrorCategory::Semantic, arg->line, arg->column, + "argument #" + std::to_string(i + 1) + " to '" + name + + "' expected '" + typeLabel(expected) + "'"); } + } else if (expected.value != ValueType::Unknown && actual.value != ValueType::Unknown && + !matchesPrimitive(expected.value, actual.value)) { + throw BlochError(ErrorCategory::Semantic, arg->line, arg->column, + "argument #" + std::to_string(i + 1) + " to '" + name + + "' expected '" + typeToString(expected.value) + "'"); } + } + }; + + if (auto var = dynamic_cast(node.callee.get())) { + MethodInfo* methodInfo = nullptr; + if (!isDeclared(var->name) && !isFunctionDeclared(var->name)) { + if (!m_currentClass.empty()) + methodInfo = findMethodInHierarchy(combine(ValueType::Unknown, m_currentClass), + var->name, &actualTypes); if (methodInfo) { - checkArgs(methodInfo->paramTypes, var->name, node.line, node.column); - } else { - size_t expected = getFunctionParamCount(var->name); - if (expected != node.arguments.size()) { + if (!isAccessible(methodInfo->visibility, methodInfo->owner, m_currentClass)) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "Function '" + var->name + "' expects " + - std::to_string(expected) + " argument(s)"); + "method '" + var->name + "' is not accessible here"); } - auto types = getFunctionParamTypes(var->name); - checkArgs(types, var->name, node.line, node.column); - } - } else if (auto member = dynamic_cast(node.callee.get())) { - if (member->object) - member->object->accept(*this); - auto objType = inferTypeInfo(member->object.get()); - if (objType.className.empty()) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "member call requires a class reference"); - } - TypeInfo searchType = objType; - if (objType.isTypeParam) { - auto bound = getTypeParamBound(objType.className); - if (!bound || bound->className.empty()) { + if (!methodInfo->isStatic && m_inStaticContext) { throw BlochError( ErrorCategory::Semantic, node.line, node.column, - "type parameter '" + objType.className + "' is not bound to a class type"); - } - searchType = *bound; - } - const ClassInfo* cls = findClass(searchType.className); - if (!cls) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "class '" + objType.className + "' not found"); - } - MethodInfo* method = findMethodInHierarchy(searchType, member->member, &actualTypes); - if (!method) { - if (findFieldInHierarchy(objType, member->member)) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'" + member->member + "' is a field and cannot be called"); - } - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "method '" + member->member + "' not found on class '" + - objType.className + "'"); - } - if (!isAccessible(method->visibility, method->owner, m_currentClass)) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "member '" + member->member + "' is not accessible here"); - } - bool objectIsType = isTypeReference(member->object.get()); - if (!method->isStatic && objectIsType) { - throw BlochError( - ErrorCategory::Semantic, node.line, node.column, - "instance method '" + member->member + "' requires an object instance"); - } - if (auto superObj = dynamic_cast(member->object.get())) { - (void)superObj; - if (m_inStaticContext) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'super' cannot be used in static context"); - } - const ClassInfo* cur = findClass(m_currentClass); - if (!cur || cur->base.empty()) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'super' used without a base class"); + "instance method '" + var->name + "' cannot be called in a static context"); } - if (method->isStatic) { + } else { + if (resolveField(var->name, var->line, var->column)) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "static methods should be accessed via the type, not super"); - } - } - auto params = method->paramTypes; - if (cls) - params = substituteMany(params, cls->typeParams, searchType.typeArgs); - checkArgs(params, member->member, node.line, node.column); - } else if (auto superCtor = dynamic_cast(node.callee.get())) { - (void)superCtor; - if (!m_inConstructor || !m_allowSuperConstructorCall) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'super(...)' is only allowed as the first statement of a " - "constructor"); - } - const ClassInfo* cur = findClass(m_currentClass); - if (!cur || cur->base.empty()) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'super' used without a base class"); - } - const ClassInfo* base = findClass(cur->base); - bool matched = false; - bool ambiguous = false; - int bestCost = std::numeric_limits::max(); - if (base) { - for (const auto& ctor : base->constructors) { - if (!isAccessible(ctor.visibility, base->name, m_currentClass)) - continue; - auto params = - substituteMany(ctor.paramTypes, base->typeParams, cur->baseType.typeArgs); - auto cost = paramsConversionCost(params, actualTypes); - if (!cost) - continue; - if (*cost < bestCost) { - bestCost = *cost; - matched = true; - ambiguous = false; - } else if (*cost == bestCost) { - ambiguous = true; - } + "'" + var->name + "' is a field and cannot be called"); } + throw BlochError(ErrorCategory::Semantic, var->line, var->column, + "Variable '" + var->name + "' not declared"); } - if (!matched) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "no accessible base constructor matches 'super(...)'"); - } - if (ambiguous) { + } + if (methodInfo) { + checkArgs(methodInfo->paramTypes, var->name, node.line, node.column); + } else { + size_t expected = getFunctionParamCount(var->name); + if (expected != node.arguments.size()) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "ambiguous base constructor call in 'super(...)'"); + "Function '" + var->name + "' expects " + + std::to_string(expected) + " argument(s)"); } - } else if (node.callee) { - node.callee->accept(*this); + auto types = getFunctionParamTypes(var->name); + checkArgs(types, var->name, node.line, node.column); } - for (auto& arg : node.arguments) arg->accept(*this); - } - - void SemanticAnalyser::visit(MemberAccessExpression& node) { - if (node.object) - node.object->accept(*this); - auto objType = inferTypeInfo(node.object.get()); + } else if (auto member = dynamic_cast(node.callee.get())) { + if (member->object) + member->object->accept(*this); + auto objType = inferTypeInfo(member->object.get()); if (objType.className.empty()) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "member access requires a class reference"); + "member call requires a class reference"); } TypeInfo searchType = objType; if (objType.isTypeParam) { @@ -2373,70 +2247,68 @@ namespace bloch::compiler { throw BlochError(ErrorCategory::Semantic, node.line, node.column, "class '" + objType.className + "' not found"); } - bool objectIsType = isTypeReference(node.object.get()); - auto* field = findFieldInHierarchy(searchType, node.member); - auto* method = findMethodInHierarchy(searchType, node.member); - if (!field && !method) { + MethodInfo* method = findMethodInHierarchy(searchType, member->member, &actualTypes); + if (!method) { + if (findFieldInHierarchy(objType, member->member)) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "'" + member->member + "' is a field and cannot be called"); + } + throw BlochError( + ErrorCategory::Semantic, node.line, node.column, + "method '" + member->member + "' not found on class '" + objType.className + "'"); + } + if (!isAccessible(method->visibility, method->owner, m_currentClass)) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "member '" + member->member + "' is not accessible here"); + } + bool objectIsType = isTypeReference(member->object.get()); + if (!method->isStatic && objectIsType) { throw BlochError( ErrorCategory::Semantic, node.line, node.column, - "member '" + node.member + "' not found on class '" + objType.className + "'"); + "instance method '" + member->member + "' requires an object instance"); } - if (field) { - if (!isAccessible(field->visibility, field->owner, m_currentClass)) { + if (auto superObj = dynamic_cast(member->object.get())) { + (void)superObj; + if (m_inStaticContext) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "member '" + node.member + "' is not accessible here"); - } - if (!field->isStatic && objectIsType) { - throw BlochError( - ErrorCategory::Semantic, node.line, node.column, - "instance field '" + node.member + "' cannot be accessed on a type"); + "'super' cannot be used in static context"); } - } else if (method) { - if (!isAccessible(method->visibility, method->owner, m_currentClass)) { + const ClassInfo* cur = findClass(m_currentClass); + if (!cur || cur->base.empty()) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "member '" + node.member + "' is not accessible here"); - } - if (!method->isStatic && objectIsType) { - throw BlochError( - ErrorCategory::Semantic, node.line, node.column, - "instance method '" + node.member + "' requires an object instance"); + "'super' used without a base class"); } - if (m_inStaticContext && method->owner == m_currentClass && !method->isStatic && - isThisReference(node.object.get())) { - throw BlochError( - ErrorCategory::Semantic, node.line, node.column, - "cannot call instance method '" + node.member + "' from static context"); + if (method->isStatic) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "static methods should be accessed via the type, not super"); } } - } - - void SemanticAnalyser::visit(NewExpression& node) { - auto cls = typeFromAst(node.classType.get()); - if (cls.isTypeParam) { + auto params = method->paramTypes; + if (cls) + params = substituteMany(params, cls->typeParams, searchType.typeArgs); + checkArgs(params, member->member, node.line, node.column); + } else if (auto superCtor = dynamic_cast(node.callee.get())) { + (void)superCtor; + if (!m_inConstructor || !m_allowSuperConstructorCall) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "cannot instantiate type parameter '" + cls.className + "'"); + "'super(...)' is only allowed as the first statement of a " + "constructor"); } - if (!cls.className.empty()) { - const ClassInfo* info = findClass(cls.className); - if (!info) - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "class '" + cls.className + "' not found"); - if (info->isStatic || info->isAbstract) { - throw BlochError( - ErrorCategory::Semantic, node.line, node.column, - "cannot instantiate static or abstract class '" + cls.className + "'"); - } - std::vector actualTypes; - actualTypes.reserve(node.arguments.size()); - for (auto& arg : node.arguments) actualTypes.push_back(inferTypeInfo(arg.get())); - bool matched = false; - bool ambiguous = false; - int bestCost = std::numeric_limits::max(); - for (const auto& ctor : info->constructors) { - if (!isAccessible(ctor.visibility, info->name, m_currentClass)) + const ClassInfo* cur = findClass(m_currentClass); + if (!cur || cur->base.empty()) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "'super' used without a base class"); + } + const ClassInfo* base = findClass(cur->base); + bool matched = false; + bool ambiguous = false; + int bestCost = std::numeric_limits::max(); + if (base) { + for (const auto& ctor : base->constructors) { + if (!isAccessible(ctor.visibility, base->name, m_currentClass)) continue; - auto params = ctor.paramTypes; - params = substituteMany(params, info->typeParams, cls.typeArgs); + auto params = + substituteMany(ctor.paramTypes, base->typeParams, cur->baseType.typeArgs); auto cost = paramsConversionCost(params, actualTypes); if (!cost) continue; @@ -2448,190 +2320,220 @@ namespace bloch::compiler { ambiguous = true; } } - if (!matched) { - throw BlochError( - ErrorCategory::Semantic, node.line, node.column, - "no accessible constructor found for class '" + cls.className + "'"); - } - if (ambiguous) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "ambiguous constructor call for class '" + cls.className + "'"); - } } - for (auto& arg : node.arguments) - if (arg) - arg->accept(*this); + if (!matched) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "no accessible base constructor matches 'super(...)'"); + } + if (ambiguous) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "ambiguous base constructor call in 'super(...)'"); + } + } else if (node.callee) { + node.callee->accept(*this); } + for (auto& arg : node.arguments) + arg->accept(*this); +} - void SemanticAnalyser::visit(ThisExpression& node) { - if (m_currentClass.empty()) { +void SemanticAnalyser::visit(MemberAccessExpression& node) { + if (node.object) + node.object->accept(*this); + auto objType = inferTypeInfo(node.object.get()); + if (objType.className.empty()) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "member access requires a class reference"); + } + TypeInfo searchType = objType; + if (objType.isTypeParam) { + auto bound = getTypeParamBound(objType.className); + if (!bound || bound->className.empty()) { + throw BlochError( + ErrorCategory::Semantic, node.line, node.column, + "type parameter '" + objType.className + "' is not bound to a class type"); + } + searchType = *bound; + } + const ClassInfo* cls = findClass(searchType.className); + if (!cls) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "class '" + objType.className + "' not found"); + } + bool objectIsType = isTypeReference(node.object.get()); + auto* field = findFieldInHierarchy(searchType, node.member); + auto* method = findMethodInHierarchy(searchType, node.member); + if (!field && !method) { + throw BlochError( + ErrorCategory::Semantic, node.line, node.column, + "member '" + node.member + "' not found on class '" + objType.className + "'"); + } + if (field) { + if (!isAccessible(field->visibility, field->owner, m_currentClass)) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "member '" + node.member + "' is not accessible here"); + } + if (!field->isStatic && objectIsType) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "instance field '" + node.member + "' cannot be accessed on a type"); + } + } else if (method) { + if (!isAccessible(method->visibility, method->owner, m_currentClass)) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'this' may only be used inside a class instance context"); + "member '" + node.member + "' is not accessible here"); } - if (m_inStaticContext) { + if (!method->isStatic && objectIsType) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'this' may not be used in static context"); + "instance method '" + node.member + "' requires an object instance"); + } + if (m_inStaticContext && method->owner == m_currentClass && !method->isStatic && + isThisReference(node.object.get())) { + throw BlochError( + ErrorCategory::Semantic, node.line, node.column, + "cannot call instance method '" + node.member + "' from static context"); } } +} - void SemanticAnalyser::visit(SuperExpression& node) { - if (m_currentClass.empty()) { +void SemanticAnalyser::visit(NewExpression& node) { + auto cls = typeFromAst(node.classType.get()); + if (cls.isTypeParam) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "cannot instantiate type parameter '" + cls.className + "'"); + } + if (!cls.className.empty()) { + const ClassInfo* info = findClass(cls.className); + if (!info) + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "class '" + cls.className + "' not found"); + if (info->isStatic || info->isAbstract) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'super' may only be used inside a class"); + "cannot instantiate static or abstract class '" + cls.className + "'"); } - if (m_inStaticContext) { + std::vector actualTypes; + actualTypes.reserve(node.arguments.size()); + for (auto& arg : node.arguments) + actualTypes.push_back(inferTypeInfo(arg.get())); + bool matched = false; + bool ambiguous = false; + int bestCost = std::numeric_limits::max(); + for (const auto& ctor : info->constructors) { + if (!isAccessible(ctor.visibility, info->name, m_currentClass)) + continue; + auto params = ctor.paramTypes; + params = substituteMany(params, info->typeParams, cls.typeArgs); + auto cost = paramsConversionCost(params, actualTypes); + if (!cost) + continue; + if (*cost < bestCost) { + bestCost = *cost; + matched = true; + ambiguous = false; + } else if (*cost == bestCost) { + ambiguous = true; + } + } + if (!matched) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'super' may not be used in static context"); + "no accessible constructor found for class '" + cls.className + "'"); } - const ClassInfo* cur = findClass(m_currentClass); - if (!cur || cur->base.empty()) { + if (ambiguous) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'super' used without a base class"); + "ambiguous constructor call for class '" + cls.className + "'"); } } + for (auto& arg : node.arguments) + if (arg) + arg->accept(*this); +} - void SemanticAnalyser::visit(IndexExpression& node) { - if (node.collection) - node.collection->accept(*this); - if (node.index) - node.index->accept(*this); +void SemanticAnalyser::visit(ThisExpression& node) { + if (m_currentClass.empty()) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "'this' may only be used inside a class instance context"); } - - void SemanticAnalyser::visit(ArrayLiteralExpression& node) { - for (auto& el : node.elements) - if (el) - el->accept(*this); + if (m_inStaticContext) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "'this' may not be used in static context"); } +} - void SemanticAnalyser::visit(ParenthesizedExpression& node) { - if (node.expression) - node.expression->accept(*this); +void SemanticAnalyser::visit(SuperExpression& node) { + if (m_currentClass.empty()) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "'super' may only be used inside a class"); } - - void SemanticAnalyser::visit(MeasureExpression& node) { - if (node.qubit) - node.qubit->accept(*this); - auto tinfo = inferTypeInfo(node.qubit.get()); - if (tinfo.value != ValueType::Unknown && tinfo.value != ValueType::Qubit) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "measure target must be a 'qubit'"); - } + if (m_inStaticContext) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "'super' may not be used in static context"); + } + const ClassInfo* cur = findClass(m_currentClass); + if (!cur || cur->base.empty()) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "'super' used without a base class"); + } +} + +void SemanticAnalyser::visit(IndexExpression& node) { + if (node.collection) + node.collection->accept(*this); + if (node.index) + node.index->accept(*this); +} + +void SemanticAnalyser::visit(ArrayLiteralExpression& node) { + for (auto& el : node.elements) + if (el) + el->accept(*this); +} + +void SemanticAnalyser::visit(ParenthesizedExpression& node) { + if (node.expression) + node.expression->accept(*this); +} + +void SemanticAnalyser::visit(MeasureExpression& node) { + if (node.qubit) + node.qubit->accept(*this); + auto tinfo = inferTypeInfo(node.qubit.get()); + if (tinfo.value != ValueType::Unknown && tinfo.value != ValueType::Qubit) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "measure target must be a 'qubit'"); } +} - void SemanticAnalyser::visit(AssignmentExpression& node) { - if (isDeclared(node.name)) { - if (isFinal(node.name)) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "Cannot assign to final variable '" + node.name + "'"); - } - if (node.value) { - TypeInfo targetType = getVariableType(node.name); - inferDiamondTypeArguments(node.value.get(), targetType, node.line, node.column); - auto valType = inferTypeInfo(node.value.get()); - if (valType.value == ValueType::Null) { - bool targetIsArray = - targetType.className.size() >= 2 && - targetType.className.rfind("[]") == targetType.className.size() - 2; - bool targetIsClass = !targetType.className.empty() && !targetIsArray; - if (!targetIsClass) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "cannot assign null to '" + node.name + "'"); - } - } else if (valType.value != ValueType::Unknown && - !isAssignableType(targetType, valType)) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "assignment to '" + node.name + "' expects '" + - typeLabel(targetType) + "'"); - } - node.value->accept(*this); - } - return; +void SemanticAnalyser::visit(AssignmentExpression& node) { + if (isDeclared(node.name)) { + if (isFinal(node.name)) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "Cannot assign to final variable '" + node.name + "'"); } - if (auto field = resolveField(node.name, node.line, node.column)) { - recordFinalFieldAssignment(*field, node.name, node.line, node.column); - if (node.value) { - TypeInfo targetType = field->type; - inferDiamondTypeArguments(node.value.get(), targetType, node.line, node.column); - auto valType = inferTypeInfo(node.value.get()); - bool fieldIsArray = + if (node.value) { + TypeInfo targetType = getVariableType(node.name); + inferDiamondTypeArguments(node.value.get(), targetType, node.line, node.column); + auto valType = inferTypeInfo(node.value.get()); + if (valType.value == ValueType::Null) { + bool targetIsArray = targetType.className.size() >= 2 && targetType.className.rfind("[]") == targetType.className.size() - 2; - if (valType.value == ValueType::Null) { - if (fieldIsArray || targetType.className.empty()) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "cannot assign null to field '" + node.name + "'"); - } - } - if (!targetType.className.empty() && valType.value != ValueType::Null && - valType.value != ValueType::Unknown && !isAssignableType(targetType, valType)) { + bool targetIsClass = !targetType.className.empty() && !targetIsArray; + if (!targetIsClass) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "assignment to field '" + node.name + "' expects '" + - typeLabel(targetType) + "'"); - } else if (field->type.value != ValueType::Unknown && - valType.value != ValueType::Unknown && - !matchesPrimitive(targetType.value, valType.value)) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "assignment to field '" + node.name + "' expects '" + - typeToString(targetType.value) + "'"); + "cannot assign null to '" + node.name + "'"); } - node.value->accept(*this); - } - return; - } - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "Variable '" + node.name + "' not declared"); - } - - void SemanticAnalyser::visit(MemberAssignmentExpression& node) { - if (node.object) - node.object->accept(*this); - auto objType = inferTypeInfo(node.object.get()); - if (objType.className.empty()) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "member assignment requires a class reference"); - } - TypeInfo searchType = objType; - if (objType.isTypeParam) { - auto bound = getTypeParamBound(objType.className); - if (!bound || bound->className.empty()) { + } else if (valType.value != ValueType::Unknown && + !isAssignableType(targetType, valType)) { throw BlochError( ErrorCategory::Semantic, node.line, node.column, - "type parameter '" + objType.className + "' is not bound to a class type"); - } - searchType = *bound; - } - const ClassInfo* cls = findClass(searchType.className); - if (!cls) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "class '" + objType.className + "' not found"); - } - FieldInfo* field = findFieldInHierarchy(searchType, node.member); - if (!field) { - throw BlochError( - ErrorCategory::Semantic, node.line, node.column, - "field '" + node.member + "' not found in class '" + objType.className + "'"); - } - if (!isAccessible(field->visibility, field->owner, m_currentClass)) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "field '" + node.member + "' is not accessible here"); - } - bool objectIsType = isTypeReference(node.object.get()); - if (!field->isStatic && objectIsType) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "instance field '" + node.member + "' cannot be assigned via type"); - } - if (field->isFinal) { - bool allowed = m_inConstructor && isThisReference(node.object.get()); - if (!allowed) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "cannot assign to final field '" + node.member + "'"); + "assignment to '" + node.name + "' expects '" + typeLabel(targetType) + "'"); } - recordFinalFieldAssignment(*field, node.member, node.line, node.column); + node.value->accept(*this); } + return; + } + if (auto field = resolveField(node.name, node.line, node.column)) { + recordFinalFieldAssignment(*field, node.name, node.line, node.column); if (node.value) { TypeInfo targetType = field->type; - if (!searchType.typeArgs.empty() && cls) - targetType = substituteTypeParams(targetType, cls->typeParams, searchType.typeArgs); inferDiamondTypeArguments(node.value.get(), targetType, node.line, node.column); auto valType = inferTypeInfo(node.value.get()); bool fieldIsArray = targetType.className.size() >= 2 && @@ -2639,478 +2541,555 @@ namespace bloch::compiler { if (valType.value == ValueType::Null) { if (fieldIsArray || targetType.className.empty()) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "cannot assign null to field '" + node.member + "'"); + "cannot assign null to field '" + node.name + "'"); } } if (!targetType.className.empty() && valType.value != ValueType::Null && valType.value != ValueType::Unknown && !isAssignableType(targetType, valType)) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "assignment to field '" + node.member + "' expects '" + + "assignment to field '" + node.name + "' expects '" + typeLabel(targetType) + "'"); - } else if (targetType.value != ValueType::Unknown && + } else if (field->type.value != ValueType::Unknown && valType.value != ValueType::Unknown && !matchesPrimitive(targetType.value, valType.value)) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "assignment to field '" + node.member + "' expects '" + + "assignment to field '" + node.name + "' expects '" + typeToString(targetType.value) + "'"); } node.value->accept(*this); } + return; } + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "Variable '" + node.name + "' not declared"); +} - void SemanticAnalyser::visit(ArrayAssignmentExpression& node) { - if (node.collection) - node.collection->accept(*this); - if (node.index) - node.index->accept(*this); - if (node.value) - node.value->accept(*this); - - // Type check: array element assignment must match element type. - auto isArrayName = [](const std::string& name) { - return name.size() >= 2 && name.rfind("[]") == name.size() - 2; - }; - - TypeInfo collectionType = inferTypeInfo(node.collection.get()); - if (!isArrayName(collectionType.className) || collectionType.typeArgs.empty()) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "assignment target is not an array"); +void SemanticAnalyser::visit(MemberAssignmentExpression& node) { + if (node.object) + node.object->accept(*this); + auto objType = inferTypeInfo(node.object.get()); + if (objType.className.empty()) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "member assignment requires a class reference"); + } + TypeInfo searchType = objType; + if (objType.isTypeParam) { + auto bound = getTypeParamBound(objType.className); + if (!bound || bound->className.empty()) { + throw BlochError( + ErrorCategory::Semantic, node.line, node.column, + "type parameter '" + objType.className + "' is not bound to a class type"); } - - TypeInfo indexType = inferTypeInfo(node.index.get()); - if (indexType.value != ValueType::Int && indexType.value != ValueType::Long) { + searchType = *bound; + } + const ClassInfo* cls = findClass(searchType.className); + if (!cls) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "class '" + objType.className + "' not found"); + } + FieldInfo* field = findFieldInHierarchy(searchType, node.member); + if (!field) { + throw BlochError( + ErrorCategory::Semantic, node.line, node.column, + "field '" + node.member + "' not found in class '" + objType.className + "'"); + } + if (!isAccessible(field->visibility, field->owner, m_currentClass)) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "field '" + node.member + "' is not accessible here"); + } + bool objectIsType = isTypeReference(node.object.get()); + if (!field->isStatic && objectIsType) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "instance field '" + node.member + "' cannot be assigned via type"); + } + if (field->isFinal) { + bool allowed = m_inConstructor && isThisReference(node.object.get()); + if (!allowed) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "array index must be of type 'int' or 'long'"); - } - - TypeInfo elemType = collectionType.typeArgs.front(); - TypeInfo valType = inferTypeInfo(node.value.get()); - + "cannot assign to final field '" + node.member + "'"); + } + recordFinalFieldAssignment(*field, node.member, node.line, node.column); + } + if (node.value) { + TypeInfo targetType = field->type; + if (!searchType.typeArgs.empty() && cls) + targetType = substituteTypeParams(targetType, cls->typeParams, searchType.typeArgs); + inferDiamondTypeArguments(node.value.get(), targetType, node.line, node.column); + auto valType = inferTypeInfo(node.value.get()); + bool fieldIsArray = targetType.className.size() >= 2 && + targetType.className.rfind("[]") == targetType.className.size() - 2; if (valType.value == ValueType::Null) { - // Only class types may take null. - bool elemIsArray = isArrayName(elemType.className); - bool elemIsClass = !elemType.className.empty() && !elemIsArray; - if (!elemIsClass) { - throw BlochError( - ErrorCategory::Semantic, node.line, node.column, - "cannot assign null to array element of type '" + typeLabel(elemType) + "'"); + if (fieldIsArray || targetType.className.empty()) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "cannot assign null to field '" + node.member + "'"); } - return; } - - auto typesCompatible = - isAssignableType(elemType, valType) || - matchesPrimitive(elemType.value, valType.value) || - (elemType.value == ValueType::Int && valType.value == ValueType::Bit); - - if (!typesCompatible) { + if (!targetType.className.empty() && valType.value != ValueType::Null && + valType.value != ValueType::Unknown && !isAssignableType(targetType, valType)) { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "assignment to array element expects '" + typeLabel(elemType) + "'"); + "assignment to field '" + node.member + "' expects '" + + typeLabel(targetType) + "'"); + } else if (targetType.value != ValueType::Unknown && valType.value != ValueType::Unknown && + !matchesPrimitive(targetType.value, valType.value)) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "assignment to field '" + node.member + "' expects '" + + typeToString(targetType.value) + "'"); } + node.value->accept(*this); } +} + +void SemanticAnalyser::visit(ArrayAssignmentExpression& node) { + if (node.collection) + node.collection->accept(*this); + if (node.index) + node.index->accept(*this); + if (node.value) + node.value->accept(*this); - void SemanticAnalyser::visit(PrimitiveType&) {} - void SemanticAnalyser::visit(NamedType&) {} - void SemanticAnalyser::visit(ArrayType&) {} - void SemanticAnalyser::visit(VoidType&) {} + // Type check: array element assignment must match element type. + auto isArrayName = [](const std::string& name) { + return name.size() >= 2 && name.rfind("[]") == name.size() - 2; + }; - void SemanticAnalyser::visit(Parameter& node) { - if (node.type) - node.type->accept(*this); + TypeInfo collectionType = inferTypeInfo(node.collection.get()); + if (!isArrayName(collectionType.className) || collectionType.typeArgs.empty()) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "assignment target is not an array"); } - void SemanticAnalyser::visit(TypeParameter&) {} + TypeInfo indexType = inferTypeInfo(node.index.get()); + if (indexType.value != ValueType::Int && indexType.value != ValueType::Long) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "array index must be of type 'int' or 'long'"); + } - void SemanticAnalyser::visit(AnnotationNode&) {} - void SemanticAnalyser::visit(PackageDeclaration&) {} - void SemanticAnalyser::visit(ImportDeclaration&) {} - void SemanticAnalyser::visit(FieldDeclaration& node) { - for (const auto& ann : node.annotations) { - if (!ann) - continue; - if (ann->name == "quantum") { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'@quantum' may annotate functions only"); - } - if (ann->name == "shots") { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'@shots(N)' can only decorate the main() function."); - } - } - TypeInfo tinfo = typeFromAst(node.fieldType.get()); - if (tinfo.value == ValueType::Void) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "fields cannot have type 'void'"); + TypeInfo elemType = collectionType.typeArgs.front(); + TypeInfo valType = inferTypeInfo(node.value.get()); + + if (valType.value == ValueType::Null) { + // Only class types may take null. + bool elemIsArray = isArrayName(elemType.className); + bool elemIsClass = !elemType.className.empty() && !elemIsArray; + if (!elemIsClass) { + throw BlochError( + ErrorCategory::Semantic, node.line, node.column, + "cannot assign null to array element of type '" + typeLabel(elemType) + "'"); } + return; + } - bool savedStatic = m_inStaticContext; - m_inStaticContext = node.isStatic; - if (node.isFinal && node.isStatic && !node.initializer) { + auto typesCompatible = isAssignableType(elemType, valType) || + matchesPrimitive(elemType.value, valType.value) || + (elemType.value == ValueType::Int && valType.value == ValueType::Bit); + + if (!typesCompatible) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "assignment to array element expects '" + typeLabel(elemType) + "'"); + } +} + +void SemanticAnalyser::visit(PrimitiveType&) {} +void SemanticAnalyser::visit(NamedType&) {} +void SemanticAnalyser::visit(ArrayType&) {} +void SemanticAnalyser::visit(VoidType&) {} + +void SemanticAnalyser::visit(Parameter& node) { + if (node.type) + node.type->accept(*this); +} + +void SemanticAnalyser::visit(TypeParameter&) {} + +void SemanticAnalyser::visit(AnnotationNode&) {} +void SemanticAnalyser::visit(PackageDeclaration&) {} +void SemanticAnalyser::visit(ImportDeclaration&) {} +void SemanticAnalyser::visit(FieldDeclaration& node) { + for (const auto& ann : node.annotations) { + if (!ann) + continue; + if (ann->name == "quantum") { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "final static field '" + node.name + "' must be initialised"); + "'@quantum' may annotate functions only"); } - if (node.initializer) { - validateTypedInitializer(node.name, node.fieldType.get(), node.initializer.get(), - node.line, node.column); + if (ann->name == "shots") { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "'@shots(N)' can only decorate the main() function."); } - m_inStaticContext = savedStatic; + } + TypeInfo tinfo = typeFromAst(node.fieldType.get()); + if (tinfo.value == ValueType::Void) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "fields cannot have type 'void'"); } - void SemanticAnalyser::visit(MethodDeclaration& node) { - // Only analyse bodies for now. - TypeInfo ret = typeFromAst(node.returnType.get()); - for (const auto& ann : node.annotations) { - if (ann && ann->name == "shots") { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'@shots(N)' can only decorate the main() function."); - } - } - if (node.hasQuantumAnnotation) { - bool valid = false; - if (ret.className.empty() && - (ret.value == ValueType::Bit || ret.value == ValueType::Void)) - valid = true; - if (ret.className == "bit[]") - valid = true; - if (!valid) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'@quantum' methods must return 'bit', 'bit[]', or 'void'"); - } - } - auto savedReturn = m_currentReturn; - auto savedClass = m_currentClass; - bool savedStatic = m_inStaticContext; - auto savedMethod = m_currentMethod; - bool savedOverride = m_currentMethodIsOverride; - bool savedCtor = m_inConstructor; - bool savedDtor = m_inDestructor; - bool savedFoundReturn = m_foundReturn; - auto restoreState = makeScopeExit([&] { - m_currentReturn = std::move(savedReturn); - m_foundReturn = savedFoundReturn; - m_currentClass = std::move(savedClass); - m_inStaticContext = savedStatic; - m_currentMethod = std::move(savedMethod); - m_currentMethodIsOverride = savedOverride; - m_inConstructor = savedCtor; - m_inDestructor = savedDtor; - }); - m_currentClass = savedClass; - m_inStaticContext = node.isStatic; - m_currentMethod = node.name; - m_currentMethodIsOverride = node.isOverride; - m_inConstructor = false; - m_inDestructor = false; - m_currentReturn = ret; - m_foundReturn = false; - - ScopeGuard scope(*this); - // 'this' binding - if (!node.isStatic && !savedClass.empty()) { - declare("this", true, combine(ValueType::Unknown, savedClass)); + bool savedStatic = m_inStaticContext; + m_inStaticContext = node.isStatic; + if (node.isFinal && node.isStatic && !node.initializer) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "final static field '" + node.name + "' must be initialised"); + } + if (node.initializer) { + validateTypedInitializer(node.name, node.fieldType.get(), node.initializer.get(), node.line, + node.column); + } + m_inStaticContext = savedStatic; +} + +void SemanticAnalyser::visit(MethodDeclaration& node) { + // Only analyse bodies for now. + TypeInfo ret = typeFromAst(node.returnType.get()); + for (const auto& ann : node.annotations) { + if (ann && ann->name == "shots") { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "'@shots(N)' can only decorate the main() function."); } + } + if (node.hasQuantumAnnotation) { + bool valid = false; + if (ret.className.empty() && (ret.value == ValueType::Bit || ret.value == ValueType::Void)) + valid = true; + if (ret.className == "bit[]") + valid = true; + if (!valid) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "'@quantum' methods must return 'bit', 'bit[]', or 'void'"); + } + } + auto savedReturn = m_currentReturn; + auto savedClass = m_currentClass; + bool savedStatic = m_inStaticContext; + auto savedMethod = m_currentMethod; + bool savedOverride = m_currentMethodIsOverride; + bool savedCtor = m_inConstructor; + bool savedDtor = m_inDestructor; + bool savedFoundReturn = m_foundReturn; + auto restoreState = makeScopeExit([&] { + m_currentReturn = std::move(savedReturn); + m_foundReturn = savedFoundReturn; + m_currentClass = std::move(savedClass); + m_inStaticContext = savedStatic; + m_currentMethod = std::move(savedMethod); + m_currentMethodIsOverride = savedOverride; + m_inConstructor = savedCtor; + m_inDestructor = savedDtor; + }); + m_currentClass = savedClass; + m_inStaticContext = node.isStatic; + m_currentMethod = node.name; + m_currentMethodIsOverride = node.isOverride; + m_inConstructor = false; + m_inDestructor = false; + m_currentReturn = ret; + m_foundReturn = false; + + ScopeGuard scope(*this); + // 'this' binding + if (!node.isStatic && !savedClass.empty()) { + declare("this", true, combine(ValueType::Unknown, savedClass)); + } + for (auto& p : node.params) { + TypeInfo pt = typeFromAst(p->type.get()); + if (isDeclared(p->name)) { + throw BlochError(ErrorCategory::Semantic, p->line, p->column, + "'" + p->name + "' is already declared in this scope"); + } + declare(p->name, false, pt); + p->accept(*this); + } + if (node.body) + node.body->accept(*this); +} + +void SemanticAnalyser::visit(ConstructorDeclaration& node) { + auto savedClass = m_currentClass; + bool savedStatic = m_inStaticContext; + bool savedCtor = m_inConstructor; + bool savedDtor = m_inDestructor; + auto savedMethod = m_currentMethod; + bool savedOverride = m_currentMethodIsOverride; + auto savedReturn = m_currentReturn; + bool savedFoundReturn = m_foundReturn; + bool savedAllowSuper = m_allowSuperConstructorCall; + auto savedCtorFinalAssignments = m_constructorFinalAssignments; + int savedCtorAssignmentDepth = m_constructorFinalAssignmentDepth; + auto restoreState = makeScopeExit([&] { + m_inStaticContext = savedStatic; + m_currentClass = std::move(savedClass); + m_inConstructor = savedCtor; + m_inDestructor = savedDtor; + m_currentMethod = std::move(savedMethod); + m_currentMethodIsOverride = savedOverride; + m_currentReturn = std::move(savedReturn); + m_foundReturn = savedFoundReturn; + m_allowSuperConstructorCall = savedAllowSuper; + m_constructorFinalAssignments = std::move(savedCtorFinalAssignments); + m_constructorFinalAssignmentDepth = savedCtorAssignmentDepth; + }); + m_constructorFinalAssignments.clear(); + m_constructorFinalAssignmentDepth = 0; + m_inStaticContext = false; + m_inConstructor = true; + m_inDestructor = false; + m_currentMethod = ""; + m_currentMethodIsOverride = false; + m_currentReturn = combine(ValueType::Unknown, savedClass); + m_foundReturn = false; + ScopeGuard scope(*this); + if (!savedClass.empty()) + declare("this", true, combine(ValueType::Unknown, savedClass)); + for (auto& p : node.params) { + TypeInfo pt = typeFromAst(p->type.get()); + if (isDeclared(p->name)) { + throw BlochError(ErrorCategory::Semantic, p->line, p->column, + "'" + p->name + "' is already declared in this scope"); + } + declare(p->name, false, pt); + p->accept(*this); + } + const ClassInfo* ctorClassInfo = findClass(savedClass); + if (ctorClassInfo && node.isDefault) { for (auto& p : node.params) { - TypeInfo pt = typeFromAst(p->type.get()); - if (isDeclared(p->name)) { + auto it = ctorClassInfo->fields.find(p->name); + if (it == ctorClassInfo->fields.end()) + continue; + const FieldInfo& f = it->second; + if (f.isStatic || !f.isFinal) + continue; + if (f.hasInitializer) { throw BlochError(ErrorCategory::Semantic, p->line, p->column, - "'" + p->name + "' is already declared in this scope"); + "default constructor cannot bind final field '" + p->name + + "' because it already has a declaration initialiser"); } - declare(p->name, false, pt); - p->accept(*this); - } - if (node.body) - node.body->accept(*this); - } - - void SemanticAnalyser::visit(ConstructorDeclaration& node) { - auto savedClass = m_currentClass; - bool savedStatic = m_inStaticContext; - bool savedCtor = m_inConstructor; - bool savedDtor = m_inDestructor; - auto savedMethod = m_currentMethod; - bool savedOverride = m_currentMethodIsOverride; - auto savedReturn = m_currentReturn; - bool savedFoundReturn = m_foundReturn; - bool savedAllowSuper = m_allowSuperConstructorCall; - auto savedCtorFinalAssignments = m_constructorFinalAssignments; - int savedCtorAssignmentDepth = m_constructorFinalAssignmentDepth; - auto restoreState = makeScopeExit([&] { - m_inStaticContext = savedStatic; - m_currentClass = std::move(savedClass); - m_inConstructor = savedCtor; - m_inDestructor = savedDtor; - m_currentMethod = std::move(savedMethod); - m_currentMethodIsOverride = savedOverride; - m_currentReturn = std::move(savedReturn); - m_foundReturn = savedFoundReturn; - m_allowSuperConstructorCall = savedAllowSuper; - m_constructorFinalAssignments = std::move(savedCtorFinalAssignments); - m_constructorFinalAssignmentDepth = savedCtorAssignmentDepth; - }); - m_constructorFinalAssignments.clear(); - m_constructorFinalAssignmentDepth = 0; - m_inStaticContext = false; - m_inConstructor = true; - m_inDestructor = false; - m_currentMethod = ""; - m_currentMethodIsOverride = false; - m_currentReturn = combine(ValueType::Unknown, savedClass); - m_foundReturn = false; - ScopeGuard scope(*this); - if (!savedClass.empty()) - declare("this", true, combine(ValueType::Unknown, savedClass)); - for (auto& p : node.params) { - TypeInfo pt = typeFromAst(p->type.get()); - if (isDeclared(p->name)) { - throw BlochError(ErrorCategory::Semantic, p->line, p->column, - "'" + p->name + "' is already declared in this scope"); + std::string key = f.owner + "::" + p->name; + int& assignmentCount = m_constructorFinalAssignments[key]; + assignmentCount += 1; + if (assignmentCount > 1) { + throw BlochError( + ErrorCategory::Semantic, p->line, p->column, + "final field '" + p->name + "' may only be assigned once in a constructor"); } - declare(p->name, false, pt); - p->accept(*this); - } - const ClassInfo* ctorClassInfo = findClass(savedClass); - if (ctorClassInfo && node.isDefault) { - for (auto& p : node.params) { - auto it = ctorClassInfo->fields.find(p->name); - if (it == ctorClassInfo->fields.end()) - continue; - const FieldInfo& f = it->second; - if (f.isStatic || !f.isFinal) - continue; - if (f.hasInitializer) { - throw BlochError(ErrorCategory::Semantic, p->line, p->column, - "default constructor cannot bind final field '" + p->name + - "' because it already has a declaration initialiser"); + } + } + bool superSeen = false; + if (node.body) { + auto& stmts = node.body->statements; + for (size_t i = 0; i < stmts.size(); ++i) { + bool isSuper = isSuperConstructorCall(stmts[i].get()); + if (isSuper) { + if (superSeen) { + throw BlochError(ErrorCategory::Semantic, stmts[i]->line, stmts[i]->column, + "constructor may only call 'super(...)' once"); } - std::string key = f.owner + "::" + p->name; - int& assignmentCount = m_constructorFinalAssignments[key]; - assignmentCount += 1; - if (assignmentCount > 1) { - throw BlochError( - ErrorCategory::Semantic, p->line, p->column, - "final field '" + p->name + "' may only be assigned once in a constructor"); + if (i != 0) { + throw BlochError(ErrorCategory::Semantic, stmts[i]->line, stmts[i]->column, + "'super(...)' must be the first statement in a " + "constructor"); } + superSeen = true; + m_allowSuperConstructorCall = true; + stmts[i]->accept(*this); + m_allowSuperConstructorCall = false; + } else { + stmts[i]->accept(*this); + if (dynamic_cast(stmts[i].get())) + break; } } - bool superSeen = false; - if (node.body) { - auto& stmts = node.body->statements; - for (size_t i = 0; i < stmts.size(); ++i) { - bool isSuper = isSuperConstructorCall(stmts[i].get()); - if (isSuper) { - if (superSeen) { - throw BlochError(ErrorCategory::Semantic, stmts[i]->line, stmts[i]->column, - "constructor may only call 'super(...)' once"); - } - if (i != 0) { - throw BlochError(ErrorCategory::Semantic, stmts[i]->line, stmts[i]->column, - "'super(...)' must be the first statement in a " - "constructor"); - } - superSeen = true; - m_allowSuperConstructorCall = true; - stmts[i]->accept(*this); - m_allowSuperConstructorCall = false; - } else { - stmts[i]->accept(*this); - if (dynamic_cast(stmts[i].get())) - break; + } + if (ctorClassInfo && !superSeen && !ctorClassInfo->base.empty()) { + const ClassInfo* base = findClass(ctorClassInfo->base); + bool matched = false; + bool ambiguous = false; + int bestCost = std::numeric_limits::max(); + const std::vector noArgs; + if (base) { + for (const auto& ctor : base->constructors) { + if (!isAccessible(ctor.visibility, base->name, m_currentClass)) + continue; + auto params = substituteMany(ctor.paramTypes, base->typeParams, + ctorClassInfo->baseType.typeArgs); + auto cost = paramsConversionCost(params, noArgs); + if (!cost) + continue; + if (*cost < bestCost) { + bestCost = *cost; + matched = true; + ambiguous = false; + } else if (*cost == bestCost) { + ambiguous = true; } } } - if (ctorClassInfo && !superSeen && !ctorClassInfo->base.empty()) { - const ClassInfo* base = findClass(ctorClassInfo->base); - bool matched = false; - bool ambiguous = false; - int bestCost = std::numeric_limits::max(); - const std::vector noArgs; - if (base) { - for (const auto& ctor : base->constructors) { - if (!isAccessible(ctor.visibility, base->name, m_currentClass)) - continue; - auto params = substituteMany(ctor.paramTypes, base->typeParams, - ctorClassInfo->baseType.typeArgs); - auto cost = paramsConversionCost(params, noArgs); - if (!cost) - continue; - if (*cost < bestCost) { - bestCost = *cost; - matched = true; - ambiguous = false; - } else if (*cost == bestCost) { - ambiguous = true; - } - } - } - if (!matched) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "no accessible base constructor matches implicit super()"); - } - if (ambiguous) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "ambiguous implicit super() constructor call"); - } + if (!matched) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "no accessible base constructor matches implicit super()"); } - if (ctorClassInfo) { - for (const auto& entry : ctorClassInfo->fields) { - const std::string& fieldName = entry.first; - const FieldInfo& field = entry.second; - if (field.isStatic || !field.isFinal || field.hasInitializer) - continue; - std::string key = field.owner + "::" + fieldName; - auto it = m_constructorFinalAssignments.find(key); - if (it == m_constructorFinalAssignments.end() || it->second == 0) { - throw BlochError( - ErrorCategory::Semantic, node.line, node.column, - "final field '" + fieldName + "' must be initialised in every constructor"); - } + if (ambiguous) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "ambiguous implicit super() constructor call"); + } + } + if (ctorClassInfo) { + for (const auto& entry : ctorClassInfo->fields) { + const std::string& fieldName = entry.first; + const FieldInfo& field = entry.second; + if (field.isStatic || !field.isFinal || field.hasInitializer) + continue; + std::string key = field.owner + "::" + fieldName; + auto it = m_constructorFinalAssignments.find(key); + if (it == m_constructorFinalAssignments.end() || it->second == 0) { + throw BlochError( + ErrorCategory::Semantic, node.line, node.column, + "final field '" + fieldName + "' must be initialised in every constructor"); } } } +} - void SemanticAnalyser::visit(DestructorDeclaration& node) { - auto savedClass = m_currentClass; - bool savedStatic = m_inStaticContext; - bool savedCtor = m_inConstructor; - bool savedDtor = m_inDestructor; - auto savedMethod = m_currentMethod; - bool savedOverride = m_currentMethodIsOverride; - auto restoreState = makeScopeExit([&] { - m_inStaticContext = savedStatic; - m_currentClass = std::move(savedClass); - m_inConstructor = savedCtor; - m_inDestructor = savedDtor; - m_currentMethod = std::move(savedMethod); - m_currentMethodIsOverride = savedOverride; - }); - m_inStaticContext = false; - m_inConstructor = false; - m_inDestructor = true; - m_currentMethod = ""; - m_currentMethodIsOverride = false; - ScopeGuard scope(*this); - if (!savedClass.empty()) - declare("this", true, combine(ValueType::Unknown, savedClass)); - if (node.body) - node.body->accept(*this); - } - - void SemanticAnalyser::visit(ClassDeclaration& node) { - // Visit member bodies minimally. - auto savedClass = m_currentClass; - auto savedParams = m_currentTypeParams; - auto restoreState = makeScopeExit([&] { - m_currentClass = std::move(savedClass); - m_currentTypeParams = std::move(savedParams); - }); - m_currentClass = node.name; - auto it = m_classes.find(node.name); - if (it != m_classes.end()) - m_currentTypeParams = it->second.typeParams; - for (auto& member : node.members) { - if (auto field = dynamic_cast(member.get())) - field->accept(*this); - else if (auto m = dynamic_cast(member.get())) - m->accept(*this); - else if (auto ctor = dynamic_cast(member.get())) - ctor->accept(*this); - else if (auto dtor = dynamic_cast(member.get())) - dtor->accept(*this); - } - } - - void SemanticAnalyser::visit(FunctionDeclaration& node) { - if (node.hasQuantumAnnotation) { - bool returnTypeIsValid = false; - if (auto prim = dynamic_cast(node.returnType.get())) { - if (prim->name == "bit") - returnTypeIsValid = true; - } else if (auto arr = dynamic_cast(node.returnType.get())) { - if (auto elem = dynamic_cast(arr->elementType.get())) { - if (elem->name == "bit") - returnTypeIsValid = true; - } - } else if (dynamic_cast(node.returnType.get())) { +void SemanticAnalyser::visit(DestructorDeclaration& node) { + auto savedClass = m_currentClass; + bool savedStatic = m_inStaticContext; + bool savedCtor = m_inConstructor; + bool savedDtor = m_inDestructor; + auto savedMethod = m_currentMethod; + bool savedOverride = m_currentMethodIsOverride; + auto restoreState = makeScopeExit([&] { + m_inStaticContext = savedStatic; + m_currentClass = std::move(savedClass); + m_inConstructor = savedCtor; + m_inDestructor = savedDtor; + m_currentMethod = std::move(savedMethod); + m_currentMethodIsOverride = savedOverride; + }); + m_inStaticContext = false; + m_inConstructor = false; + m_inDestructor = true; + m_currentMethod = ""; + m_currentMethodIsOverride = false; + ScopeGuard scope(*this); + if (!savedClass.empty()) + declare("this", true, combine(ValueType::Unknown, savedClass)); + if (node.body) + node.body->accept(*this); +} + +void SemanticAnalyser::visit(ClassDeclaration& node) { + // Visit member bodies minimally. + auto savedClass = m_currentClass; + auto savedParams = m_currentTypeParams; + auto restoreState = makeScopeExit([&] { + m_currentClass = std::move(savedClass); + m_currentTypeParams = std::move(savedParams); + }); + m_currentClass = node.name; + auto it = m_classes.find(node.name); + if (it != m_classes.end()) + m_currentTypeParams = it->second.typeParams; + for (auto& member : node.members) { + if (auto field = dynamic_cast(member.get())) + field->accept(*this); + else if (auto m = dynamic_cast(member.get())) + m->accept(*this); + else if (auto ctor = dynamic_cast(member.get())) + ctor->accept(*this); + else if (auto dtor = dynamic_cast(member.get())) + dtor->accept(*this); + } +} + +void SemanticAnalyser::visit(FunctionDeclaration& node) { + if (node.hasQuantumAnnotation) { + bool returnTypeIsValid = false; + if (auto prim = dynamic_cast(node.returnType.get())) { + if (prim->name == "bit") returnTypeIsValid = true; + } else if (auto arr = dynamic_cast(node.returnType.get())) { + if (auto elem = dynamic_cast(arr->elementType.get())) { + if (elem->name == "bit") + returnTypeIsValid = true; } - - if (!returnTypeIsValid) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'@quantum' functions must return 'bit', 'bit[]', or 'void'."); - } - - // @quantum is not allowed on the main() entry point function - if (node.name == "main") { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'@quantum' cannot decorate the main() function."); - } + } else if (dynamic_cast(node.returnType.get())) { + returnTypeIsValid = true; } - int shotsCount = 0; - for (const auto& ann : node.annotations) { - if (ann && ann->name == "shots") - shotsCount++; + if (!returnTypeIsValid) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "'@quantum' functions must return 'bit', 'bit[]', or 'void'."); } - if (shotsCount > 1) { + + // @quantum is not allowed on the main() entry point function + if (node.name == "main") { throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "multiple '@shots' annotations are not allowed."); + "'@quantum' cannot decorate the main() function."); } + } - if (shotsCount > 0 || node.hasShotsAnnotation) { - bool isOnMainFunction = false; - if (node.name == "main") { - isOnMainFunction = true; - } + int shotsCount = 0; + for (const auto& ann : node.annotations) { + if (ann && ann->name == "shots") + shotsCount++; + } + if (shotsCount > 1) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "multiple '@shots' annotations are not allowed."); + } - if (!isOnMainFunction) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "'@shots(N)' can only decorate the main() function."); - } + if (shotsCount > 0 || node.hasShotsAnnotation) { + bool isOnMainFunction = false; + if (node.name == "main") { + isOnMainFunction = true; } - TypeInfo ret = typeFromAst(node.returnType.get()); - auto savedReturn = m_currentReturn; - bool prevFound = m_foundReturn; - auto restoreState = makeScopeExit([&] { - m_currentReturn = std::move(savedReturn); - m_foundReturn = prevFound; - }); - m_currentReturn = ret; - m_foundReturn = false; - - FunctionInfo info; - info.returnType = ret; - for (auto& p : node.params) { - info.paramTypes.push_back(typeFromAst(p->type.get())); + if (!isOnMainFunction) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "'@shots(N)' can only decorate the main() function."); } - m_functionInfo[node.name] = info; + } - ScopeGuard scope(*this); - for (auto& param : node.params) { - if (isDeclared(param->name)) { - throw BlochError(ErrorCategory::Semantic, param->line, param->column, - "'" + param->name + "' is already declared in this scope"); - } - TypeInfo pt = typeFromAst(param->type.get()); - if (pt.value == ValueType::Void) { - throw BlochError(ErrorCategory::Semantic, param->line, param->column, - "parameters cannot have type 'void'"); - } - declare(param->name, false, pt); - param->accept(*this); + TypeInfo ret = typeFromAst(node.returnType.get()); + auto savedReturn = m_currentReturn; + bool prevFound = m_foundReturn; + auto restoreState = makeScopeExit([&] { + m_currentReturn = std::move(savedReturn); + m_foundReturn = prevFound; + }); + m_currentReturn = ret; + m_foundReturn = false; + + FunctionInfo info; + info.returnType = ret; + for (auto& p : node.params) { + info.paramTypes.push_back(typeFromAst(p->type.get())); + } + m_functionInfo[node.name] = info; + + ScopeGuard scope(*this); + for (auto& param : node.params) { + if (isDeclared(param->name)) { + throw BlochError(ErrorCategory::Semantic, param->line, param->column, + "'" + param->name + "' is already declared in this scope"); } - if (node.body) - node.body->accept(*this); - if (ret.value != ValueType::Void || !ret.className.empty()) { - if (!m_foundReturn) { - throw BlochError(ErrorCategory::Semantic, node.line, node.column, - "Non-void function must have a 'return' statement."); - } + TypeInfo pt = typeFromAst(param->type.get()); + if (pt.value == ValueType::Void) { + throw BlochError(ErrorCategory::Semantic, param->line, param->column, + "parameters cannot have type 'void'"); } + declare(param->name, false, pt); + param->accept(*this); } - - void SemanticAnalyser::visit(Program&) { - // handled in analyse + if (node.body) + node.body->accept(*this); + if (ret.value != ValueType::Void || !ret.className.empty()) { + if (!m_foundReturn) { + throw BlochError(ErrorCategory::Semantic, node.line, node.column, + "Non-void function must have a 'return' statement."); + } } +} + +void SemanticAnalyser::visit(Program&) { + // handled in analyse +} } // namespace bloch::compiler diff --git a/src/bloch/compiler/semantics/semantic_analyser.hpp b/src/bloch/compiler/semantics/semantic_analyser.hpp index 48260d4..a3d7701 100644 --- a/src/bloch/compiler/semantics/semantic_analyser.hpp +++ b/src/bloch/compiler/semantics/semantic_analyser.hpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -26,232 +26,232 @@ namespace bloch::compiler { - // The semantic pass checks name usage, types at a coarse level, - // function contracts, and a few language rules (like @tracked constraints). - // It also records function signatures for later runtime validation. - class SemanticAnalyser : public ASTVisitor { - public: - void analyse(Program& program); +// The semantic pass checks name usage, types at a coarse level, +// function contracts, and a few language rules (like @tracked constraints). +// It also records function signatures for later runtime validation. +class SemanticAnalyser : public ASTVisitor { + public: + void analyse(Program& program); - struct TypeInfo { - ValueType value = ValueType::Unknown; - std::string className; // non-empty when referring to a user-defined class - std::vector typeArgs; - bool isTypeParam = false; - bool isClass() const { return !className.empty(); } - }; + struct TypeInfo { + ValueType value = ValueType::Unknown; + std::string className; // non-empty when referring to a user-defined class + std::vector typeArgs; + bool isTypeParam = false; + bool isClass() const { return !className.empty(); } + }; - static bool typeEquals(const TypeInfo& a, const TypeInfo& b); - static std::string typeLabel(const TypeInfo& t); + static bool typeEquals(const TypeInfo& a, const TypeInfo& b); + static std::string typeLabel(const TypeInfo& t); - // Visitors - void visit(VariableDeclaration& node) override; - void visit(BlockStatement& node) override; - void visit(ExpressionStatement& node) override; - void visit(ReturnStatement& node) override; - void visit(IfStatement& node) override; - void visit(TernaryStatement& node) override; - void visit(ForStatement& node) override; - void visit(WhileStatement& node) override; - void visit(EchoStatement& node) override; - void visit(ResetStatement& node) override; - void visit(MeasureStatement& node) override; - void visit(DestroyStatement& node) override; - void visit(AssignmentStatement& node) override; + // Visitors + void visit(VariableDeclaration& node) override; + void visit(BlockStatement& node) override; + void visit(ExpressionStatement& node) override; + void visit(ReturnStatement& node) override; + void visit(IfStatement& node) override; + void visit(TernaryStatement& node) override; + void visit(ForStatement& node) override; + void visit(WhileStatement& node) override; + void visit(EchoStatement& node) override; + void visit(ResetStatement& node) override; + void visit(MeasureStatement& node) override; + void visit(DestroyStatement& node) override; + void visit(AssignmentStatement& node) override; - void visit(BinaryExpression& node) override; - void visit(UnaryExpression& node) override; - void visit(CastExpression& node) override; - void visit(PostfixExpression& node) override; - void visit(LiteralExpression& node) override; - void visit(NullLiteralExpression& node) override; - void visit(VariableExpression& node) override; - void visit(CallExpression& node) override; - void visit(MemberAccessExpression& node) override; - void visit(NewExpression& node) override; - void visit(ThisExpression& node) override; - void visit(SuperExpression& node) override; - void visit(IndexExpression& node) override; - void visit(ArrayLiteralExpression& node) override; - void visit(ParenthesizedExpression& node) override; - void visit(MeasureExpression& node) override; - void visit(AssignmentExpression& node) override; - void visit(MemberAssignmentExpression& node) override; - void visit(ArrayAssignmentExpression& node) override; + void visit(BinaryExpression& node) override; + void visit(UnaryExpression& node) override; + void visit(CastExpression& node) override; + void visit(PostfixExpression& node) override; + void visit(LiteralExpression& node) override; + void visit(NullLiteralExpression& node) override; + void visit(VariableExpression& node) override; + void visit(CallExpression& node) override; + void visit(MemberAccessExpression& node) override; + void visit(NewExpression& node) override; + void visit(ThisExpression& node) override; + void visit(SuperExpression& node) override; + void visit(IndexExpression& node) override; + void visit(ArrayLiteralExpression& node) override; + void visit(ParenthesizedExpression& node) override; + void visit(MeasureExpression& node) override; + void visit(AssignmentExpression& node) override; + void visit(MemberAssignmentExpression& node) override; + void visit(ArrayAssignmentExpression& node) override; - void visit(PrimitiveType& node) override; - void visit(NamedType& node) override; - void visit(ArrayType& node) override; - void visit(VoidType& node) override; + void visit(PrimitiveType& node) override; + void visit(NamedType& node) override; + void visit(ArrayType& node) override; + void visit(VoidType& node) override; - void visit(Parameter& node) override; - void visit(TypeParameter& node) override; - void visit(AnnotationNode& node) override; - void visit(PackageDeclaration& node) override; - void visit(ImportDeclaration& node) override; - void visit(FieldDeclaration& node) override; - void visit(MethodDeclaration& node) override; - void visit(ConstructorDeclaration& node) override; - void visit(DestructorDeclaration& node) override; - void visit(ClassDeclaration& node) override; - void visit(FunctionDeclaration& node) override; - void visit(Program& node) override; + void visit(Parameter& node) override; + void visit(TypeParameter& node) override; + void visit(AnnotationNode& node) override; + void visit(PackageDeclaration& node) override; + void visit(ImportDeclaration& node) override; + void visit(FieldDeclaration& node) override; + void visit(MethodDeclaration& node) override; + void visit(ConstructorDeclaration& node) override; + void visit(DestructorDeclaration& node) override; + void visit(ClassDeclaration& node) override; + void visit(FunctionDeclaration& node) override; + void visit(Program& node) override; - private: - // Ensures beginScope/endScope are paired during stack unwinding. - class ScopeGuard { - public: - explicit ScopeGuard(SemanticAnalyser& analyser) : m_analyser(analyser) { - m_analyser.beginScope(); - } - ~ScopeGuard() { m_analyser.endScope(); } - ScopeGuard(const ScopeGuard&) = delete; - ScopeGuard& operator=(const ScopeGuard&) = delete; + private: + // Ensures beginScope/endScope are paired during stack unwinding. + class ScopeGuard { + public: + explicit ScopeGuard(SemanticAnalyser& analyser) : m_analyser(analyser) { + m_analyser.beginScope(); + } + ~ScopeGuard() { m_analyser.endScope(); } + ScopeGuard(const ScopeGuard&) = delete; + ScopeGuard& operator=(const ScopeGuard&) = delete; - private: - SemanticAnalyser& m_analyser; - }; + private: + SemanticAnalyser& m_analyser; + }; - SymbolTable m_symbols; - TypeInfo m_currentReturn; - bool m_foundReturn = false; - std::unordered_set m_functions; + SymbolTable m_symbols; + TypeInfo m_currentReturn; + bool m_foundReturn = false; + std::unordered_set m_functions; - struct FunctionInfo { - TypeInfo returnType; - std::vector paramTypes; - }; - std::unordered_map m_functionInfo; + struct FunctionInfo { + TypeInfo returnType; + std::vector paramTypes; + }; + std::unordered_map m_functionInfo; - struct FieldInfo { - Visibility visibility = Visibility::Public; - bool isStatic = false; - bool isFinal = false; - bool hasInitializer = false; - bool isTracked = false; - TypeInfo type; - std::string owner; - int line = 0; - int column = 0; - }; + struct FieldInfo { + Visibility visibility = Visibility::Public; + bool isStatic = false; + bool isFinal = false; + bool hasInitializer = false; + bool isTracked = false; + TypeInfo type; + std::string owner; + int line = 0; + int column = 0; + }; - struct MethodInfo { - Visibility visibility = Visibility::Public; - bool isStatic = false; - bool isVirtual = false; - bool isOverride = false; - bool hasBody = false; - bool isDefault = false; // used for constructors - std::string name; - std::string signature; - TypeInfo returnType; - std::vector paramTypes; - std::string owner; - int line = 0; - int column = 0; - }; + struct MethodInfo { + Visibility visibility = Visibility::Public; + bool isStatic = false; + bool isVirtual = false; + bool isOverride = false; + bool hasBody = false; + bool isDefault = false; // used for constructors + std::string name; + std::string signature; + TypeInfo returnType; + std::vector paramTypes; + std::string owner; + int line = 0; + int column = 0; + }; - struct ClassInfo { + struct ClassInfo { + std::string name; + std::string base; + // The declared base, including specialisation arguments such as Base. + // `base` remains the simple name used for hierarchy traversal. + TypeInfo baseType; + bool isStatic = false; + bool isAbstract = false; + bool hasDestructor = true; // implicit default exists + bool hasUserDestructor = false; // true if explicitly declared + struct TypeParamInfo { std::string name; - std::string base; - // The declared base, including specialisation arguments such as Base. - // `base` remains the simple name used for hierarchy traversal. - TypeInfo baseType; - bool isStatic = false; - bool isAbstract = false; - bool hasDestructor = true; // implicit default exists - bool hasUserDestructor = false; // true if explicitly declared - struct TypeParamInfo { - std::string name; - TypeInfo bound; - }; - std::vector typeParams; - std::vector abstractMethods; - std::unordered_map fields; - std::unordered_map> methods; - std::unordered_set methodSignatures; - std::vector constructors; - std::vector ctorDecls; // raw pointers owned by AST - int line = 0; - int column = 0; + TypeInfo bound; }; + std::vector typeParams; + std::vector abstractMethods; + std::unordered_map fields; + std::unordered_map> methods; + std::unordered_set methodSignatures; + std::vector constructors; + std::vector ctorDecls; // raw pointers owned by AST + int line = 0; + int column = 0; + }; - std::unordered_map m_classes; - std::string m_currentClass; - bool m_inStaticContext = false; - bool m_inConstructor = false; - bool m_inDestructor = false; - bool m_allowSuperConstructorCall = false; - std::string m_currentMethod; - bool m_currentMethodIsOverride = false; + std::unordered_map m_classes; + std::string m_currentClass; + bool m_inStaticContext = false; + bool m_inConstructor = false; + bool m_inDestructor = false; + bool m_allowSuperConstructorCall = false; + std::string m_currentMethod; + bool m_currentMethodIsOverride = false; - // Track full type information (including generic arguments) alongside the symbol table. - std::vector> m_typeStack; + // Track full type information (including generic arguments) alongside the symbol table. + std::vector> m_typeStack; - // Helpers - void beginScope(); - void endScope(); - void declare(const std::string& name, bool isFinal, const TypeInfo& type, - bool isTypeName = false); - bool isDeclared(const std::string& name) const; - void declareFunction(const std::string& name); - bool isFunctionDeclared(const std::string& name) const; - bool isFinal(const std::string& name) const; - size_t getFunctionParamCount(const std::string& name) const; - std::vector getFunctionParamTypes(const std::string& name) const; - TypeInfo getVariableType(const std::string& name) const; - std::string getVariableClassName(const std::string& name) const; - bool returnsVoid(const std::string& name) const; - TypeInfo typeFromAst(Type* typeNode) const; - static TypeInfo combine(ValueType prim, const std::string& cls); - TypeInfo inferTypeInfo(Expression* expr) const; - void buildClassRegistry(Program& program); - const ClassInfo* findClass(const std::string& name) const; - MethodInfo* findMethodInHierarchy(const TypeInfo& classType, const std::string& method, - const std::vector* params = nullptr) const; - FieldInfo* findFieldInHierarchy(const TypeInfo& classType, const std::string& field) const; - const FieldInfo* resolveField(const std::string& name, int line, int column) const; - bool isSubclassOf(const std::string& derived, const std::string& base) const; - int inheritanceDistance(const std::string& derived, const std::string& base) const; - bool isAssignableType(const TypeInfo& expected, const TypeInfo& actual) const; - bool paramsAssignable(const std::vector& expected, - const std::vector& actual) const; - std::optional conversionCost(const TypeInfo& expected, const TypeInfo& actual) const; - std::optional paramsConversionCost(const std::vector& expected, - const std::vector& actual) const; - void validateOverrides(ClassInfo& info); - void validateAbstractness(ClassInfo& info); - bool isAccessible(Visibility visibility, const std::string& owner, - const std::string& accessor) const; - bool isTypeReference(Expression* expr) const; - bool isThisReference(Expression* expr) const; - bool isSuperConstructorCall(Statement* stmt) const; - std::unique_ptr typeFromTypeInfo(const TypeInfo& typeInfo) const; - void inferDiamondTypeArguments(Expression* initializer, const TypeInfo& expectedType, - int line, int column); - void validateTypedInitializer(const std::string& name, Type* declaredType, - Expression* initializer, int line, int column); - void recordFinalFieldAssignment(const FieldInfo& field, const std::string& fieldName, - int line, int column); + // Helpers + void beginScope(); + void endScope(); + void declare(const std::string& name, bool isFinal, const TypeInfo& type, + bool isTypeName = false); + bool isDeclared(const std::string& name) const; + void declareFunction(const std::string& name); + bool isFunctionDeclared(const std::string& name) const; + bool isFinal(const std::string& name) const; + size_t getFunctionParamCount(const std::string& name) const; + std::vector getFunctionParamTypes(const std::string& name) const; + TypeInfo getVariableType(const std::string& name) const; + std::string getVariableClassName(const std::string& name) const; + bool returnsVoid(const std::string& name) const; + TypeInfo typeFromAst(Type* typeNode) const; + static TypeInfo combine(ValueType prim, const std::string& cls); + TypeInfo inferTypeInfo(Expression* expr) const; + void buildClassRegistry(Program& program); + const ClassInfo* findClass(const std::string& name) const; + MethodInfo* findMethodInHierarchy(const TypeInfo& classType, const std::string& method, + const std::vector* params = nullptr) const; + FieldInfo* findFieldInHierarchy(const TypeInfo& classType, const std::string& field) const; + const FieldInfo* resolveField(const std::string& name, int line, int column) const; + bool isSubclassOf(const std::string& derived, const std::string& base) const; + int inheritanceDistance(const std::string& derived, const std::string& base) const; + bool isAssignableType(const TypeInfo& expected, const TypeInfo& actual) const; + bool paramsAssignable(const std::vector& expected, + const std::vector& actual) const; + std::optional conversionCost(const TypeInfo& expected, const TypeInfo& actual) const; + std::optional paramsConversionCost(const std::vector& expected, + const std::vector& actual) const; + void validateOverrides(ClassInfo& info); + void validateAbstractness(ClassInfo& info); + bool isAccessible(Visibility visibility, const std::string& owner, + const std::string& accessor) const; + bool isTypeReference(Expression* expr) const; + bool isThisReference(Expression* expr) const; + bool isSuperConstructorCall(Statement* stmt) const; + std::unique_ptr typeFromTypeInfo(const TypeInfo& typeInfo) const; + void inferDiamondTypeArguments(Expression* initializer, const TypeInfo& expectedType, int line, + int column); + void validateTypedInitializer(const std::string& name, Type* declaredType, + Expression* initializer, int line, int column); + void recordFinalFieldAssignment(const FieldInfo& field, const std::string& fieldName, int line, + int column); - // Type inference - std::optional evaluateConstInt(Expression* expr) const; + // Type inference + std::optional evaluateConstInt(Expression* expr) const; - // Generics helpers - std::vector m_currentTypeParams; - bool m_inClassRegistryBuild = false; - TypeInfo substituteTypeParams(const TypeInfo& t, - const std::vector& params, - const std::vector& args) const; - std::vector substituteMany(const std::vector& types, - const std::vector& params, - const std::vector& args) const; - void validateTypeApplication(const TypeInfo& t, int line, int column) const; - std::optional getTypeParamBound(const std::string& name) const; + // Generics helpers + std::vector m_currentTypeParams; + bool m_inClassRegistryBuild = false; + TypeInfo substituteTypeParams(const TypeInfo& t, + const std::vector& params, + const std::vector& args) const; + std::vector substituteMany(const std::vector& types, + const std::vector& params, + const std::vector& args) const; + void validateTypeApplication(const TypeInfo& t, int line, int column) const; + std::optional getTypeParamBound(const std::string& name) const; - // Tracks final-field assignments in the constructor currently being analysed. - std::unordered_map m_constructorFinalAssignments; - int m_constructorFinalAssignmentDepth = 0; - }; + // Tracks final-field assignments in the constructor currently being analysed. + std::unordered_map m_constructorFinalAssignments; + int m_constructorFinalAssignmentDepth = 0; +}; } // namespace bloch::compiler diff --git a/src/bloch/compiler/semantics/type_system.cpp b/src/bloch/compiler/semantics/type_system.cpp index cf6fd9f..a1a6391 100644 --- a/src/bloch/compiler/semantics/type_system.cpp +++ b/src/bloch/compiler/semantics/type_system.cpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,134 +16,134 @@ namespace bloch::compiler { - ValueType typeFromString(const std::string& name) { - // Map source-level type names to our compact enum. - if (name == "int") - return ValueType::Int; - if (name == "long") - return ValueType::Long; - if (name == "float") - return ValueType::Float; - if (name == "string") - return ValueType::String; - if (name == "char") - return ValueType::Char; - if (name == "qubit") - return ValueType::Qubit; - if (name == "bit") - return ValueType::Bit; - if (name == "boolean") - return ValueType::Boolean; - if (name == "null") - return ValueType::Null; - if (name == "void") - return ValueType::Void; - return ValueType::Unknown; - } +ValueType typeFromString(const std::string& name) { + // Map source-level type names to our compact enum. + if (name == "int") + return ValueType::Int; + if (name == "long") + return ValueType::Long; + if (name == "float") + return ValueType::Float; + if (name == "string") + return ValueType::String; + if (name == "char") + return ValueType::Char; + if (name == "qubit") + return ValueType::Qubit; + if (name == "bit") + return ValueType::Bit; + if (name == "boolean") + return ValueType::Boolean; + if (name == "null") + return ValueType::Null; + if (name == "void") + return ValueType::Void; + return ValueType::Unknown; +} - std::string typeToString(ValueType type) { - // The reverse mapping comes in handy for diagnostics. - switch (type) { - case ValueType::Int: - return "int"; - case ValueType::Long: - return "long"; - case ValueType::Float: - return "float"; - case ValueType::String: - return "string"; - case ValueType::Char: - return "char"; - case ValueType::Qubit: - return "qubit"; - case ValueType::Bit: - return "bit"; - case ValueType::Boolean: - return "boolean"; - case ValueType::Null: - return "null"; - case ValueType::Void: - return "void"; - default: - return "unknown"; - } +std::string typeToString(ValueType type) { + // The reverse mapping comes in handy for diagnostics. + switch (type) { + case ValueType::Int: + return "int"; + case ValueType::Long: + return "long"; + case ValueType::Float: + return "float"; + case ValueType::String: + return "string"; + case ValueType::Char: + return "char"; + case ValueType::Qubit: + return "qubit"; + case ValueType::Bit: + return "bit"; + case ValueType::Boolean: + return "boolean"; + case ValueType::Null: + return "null"; + case ValueType::Void: + return "void"; + default: + return "unknown"; } +} - void SymbolTable::beginScope() { m_scopes.emplace_back(); } +void SymbolTable::beginScope() { m_scopes.emplace_back(); } - void SymbolTable::endScope() { - if (!m_scopes.empty()) - m_scopes.pop_back(); - } +void SymbolTable::endScope() { + if (!m_scopes.empty()) + m_scopes.pop_back(); +} - void SymbolTable::declare(const std::string& name, bool isFinal, ValueType type, - const std::string& className, bool isTypeName) { - if (m_scopes.empty()) - return; - m_scopes.back()[name] = SymbolInfo{isFinal, type, std::nullopt, className, isTypeName}; - } +void SymbolTable::declare(const std::string& name, bool isFinal, ValueType type, + const std::string& className, bool isTypeName) { + if (m_scopes.empty()) + return; + m_scopes.back()[name] = SymbolInfo{isFinal, type, std::nullopt, className, isTypeName}; +} - bool SymbolTable::isDeclared(const std::string& name) const { - for (auto it = m_scopes.rbegin(); it != m_scopes.rend(); ++it) { - if (it->count(name)) - return true; - } - return false; +bool SymbolTable::isDeclared(const std::string& name) const { + for (auto it = m_scopes.rbegin(); it != m_scopes.rend(); ++it) { + if (it->count(name)) + return true; } + return false; +} - bool SymbolTable::isFinal(const std::string& name) const { - for (auto it = m_scopes.rbegin(); it != m_scopes.rend(); ++it) { - auto found = it->find(name); - if (found != it->end()) - return found->second.isFinal; - } - return false; +bool SymbolTable::isFinal(const std::string& name) const { + for (auto it = m_scopes.rbegin(); it != m_scopes.rend(); ++it) { + auto found = it->find(name); + if (found != it->end()) + return found->second.isFinal; } + return false; +} - ValueType SymbolTable::getType(const std::string& name) const { - for (auto it = m_scopes.rbegin(); it != m_scopes.rend(); ++it) { - auto found = it->find(name); - if (found != it->end()) - return found->second.type; - } - return ValueType::Unknown; +ValueType SymbolTable::getType(const std::string& name) const { + for (auto it = m_scopes.rbegin(); it != m_scopes.rend(); ++it) { + auto found = it->find(name); + if (found != it->end()) + return found->second.type; } + return ValueType::Unknown; +} - std::string SymbolTable::getClassName(const std::string& name) const { - for (auto it = m_scopes.rbegin(); it != m_scopes.rend(); ++it) { - auto found = it->find(name); - if (found != it->end()) - return found->second.className; - } - return ""; +std::string SymbolTable::getClassName(const std::string& name) const { + for (auto it = m_scopes.rbegin(); it != m_scopes.rend(); ++it) { + auto found = it->find(name); + if (found != it->end()) + return found->second.className; } + return ""; +} - bool SymbolTable::isTypeName(const std::string& name) const { - for (auto it = m_scopes.rbegin(); it != m_scopes.rend(); ++it) { - auto found = it->find(name); - if (found != it->end()) - return found->second.isTypeName; - } - return false; +bool SymbolTable::isTypeName(const std::string& name) const { + for (auto it = m_scopes.rbegin(); it != m_scopes.rend(); ++it) { + auto found = it->find(name); + if (found != it->end()) + return found->second.isTypeName; } + return false; +} - std::optional SymbolTable::getConstInt(const std::string& name) const { - for (auto it = m_scopes.rbegin(); it != m_scopes.rend(); ++it) { - auto found = it->find(name); - if (found != it->end()) - return found->second.constInt; - } - return std::nullopt; +std::optional SymbolTable::getConstInt(const std::string& name) const { + for (auto it = m_scopes.rbegin(); it != m_scopes.rend(); ++it) { + auto found = it->find(name); + if (found != it->end()) + return found->second.constInt; } + return std::nullopt; +} - void SymbolTable::setConstInt(const std::string& name, int value) { - for (auto it = m_scopes.rbegin(); it != m_scopes.rend(); ++it) { - auto found = it->find(name); - if (found != it->end()) { - found->second.constInt = value; - return; - } +void SymbolTable::setConstInt(const std::string& name, int value) { + for (auto it = m_scopes.rbegin(); it != m_scopes.rend(); ++it) { + auto found = it->find(name); + if (found != it->end()) { + found->second.constInt = value; + return; } } +} } // namespace bloch::compiler diff --git a/src/bloch/compiler/semantics/type_system.hpp b/src/bloch/compiler/semantics/type_system.hpp index 04d665a..d57587e 100644 --- a/src/bloch/compiler/semantics/type_system.hpp +++ b/src/bloch/compiler/semantics/type_system.hpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -21,49 +21,37 @@ namespace bloch::compiler { - // A compact type universe for semantic checks and runtime hints. - enum class ValueType { - Int, - Long, - Float, - String, - Char, - Qubit, - Bit, - Boolean, - Null, - Void, - Unknown - }; - - ValueType typeFromString(const std::string& name); - std::string typeToString(ValueType type); - - // Per-name metadata tracked across nested scopes. - struct SymbolInfo { - bool isFinal = false; - ValueType type = ValueType::Unknown; - std::optional constInt; - std::string className; // Non-empty for user-defined classes - bool isTypeName = false; // True when the symbol represents a type (e.g. class name) - }; - - // Nested-scope symbol table (stack of hash maps). - class SymbolTable { - public: - void beginScope(); - void endScope(); - void declare(const std::string& name, bool isFinal, ValueType type, - const std::string& className = "", bool isTypeName = false); - bool isDeclared(const std::string& name) const; - bool isFinal(const std::string& name) const; - ValueType getType(const std::string& name) const; - std::string getClassName(const std::string& name) const; - bool isTypeName(const std::string& name) const; - std::optional getConstInt(const std::string& name) const; - void setConstInt(const std::string& name, int value); - - private: - std::vector> m_scopes; - }; +// A compact type universe for semantic checks and runtime hints. +enum class ValueType { Int, Long, Float, String, Char, Qubit, Bit, Boolean, Null, Void, Unknown }; + +ValueType typeFromString(const std::string& name); +std::string typeToString(ValueType type); + +// Per-name metadata tracked across nested scopes. +struct SymbolInfo { + bool isFinal = false; + ValueType type = ValueType::Unknown; + std::optional constInt; + std::string className; // Non-empty for user-defined classes + bool isTypeName = false; // True when the symbol represents a type (e.g. class name) +}; + +// Nested-scope symbol table (stack of hash maps). +class SymbolTable { + public: + void beginScope(); + void endScope(); + void declare(const std::string& name, bool isFinal, ValueType type, + const std::string& className = "", bool isTypeName = false); + bool isDeclared(const std::string& name) const; + bool isFinal(const std::string& name) const; + ValueType getType(const std::string& name) const; + std::string getClassName(const std::string& name) const; + bool isTypeName(const std::string& name) const; + std::optional getConstInt(const std::string& name) const; + void setConstInt(const std::string& name, int value); + + private: + std::vector> m_scopes; +}; } // namespace bloch::compiler diff --git a/src/bloch/http/http_client.cpp b/src/bloch/http/http_client.cpp deleted file mode 100644 index b97dfb3..0000000 --- a/src/bloch/http/http_client.cpp +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "bloch/http/http_client.hpp" - -#include - -namespace bloch::http { - - namespace { - Response notImplemented(std::string url) { - Response resp; - resp.status = 501; - resp.headers.emplace("X-Bloch-HTTP", "stub"); - resp.body = "HTTP client not yet implemented for " + std::move(url); - return resp; - } - } // namespace - - Response Client::get(std::string_view url, int timeout_ms) const { - (void)timeout_ms; - return notImplemented(std::string(url)); - } - - Response Client::post(std::string_view url, const std::string& body, Headers headers, - int timeout_ms) const { - (void)body; - (void)headers; - (void)timeout_ms; - return notImplemented(std::string(url)); - } - -} // namespace bloch::http diff --git a/src/bloch/http/http_client.hpp b/src/bloch/http/http_client.hpp deleted file mode 100644 index 39dcb2b..0000000 --- a/src/bloch/http/http_client.hpp +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#pragma once - -#include -#include -#include - -namespace bloch::http { - - using Headers = std::map; - - struct Request { - std::string method = "GET"; - std::string url; - Headers headers; - std::string body; - int timeout_ms = 5000; - }; - - struct Response { - int status = 0; - Headers headers; - std::string body; - - [[nodiscard]] bool ok() const { return status >= 200 && status < 300; } - }; - - class Client { - public: - Client() = default; - - // Basic verbs; synchronous for now. Future work: async + streaming. - [[nodiscard]] Response get(std::string_view url, int timeout_ms = 5000) const; - [[nodiscard]] Response post(std::string_view url, const std::string& body, - Headers headers = {}, int timeout_ms = 5000) const; - }; - -} // namespace bloch::http diff --git a/src/bloch/runtime/qasm_simulator.cpp b/src/bloch/runtime/qasm_simulator.cpp index 4d4faa0..92227c1 100644 --- a/src/bloch/runtime/qasm_simulator.cpp +++ b/src/bloch/runtime/qasm_simulator.cpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,230 +22,232 @@ namespace bloch::runtime { - using support::BlochError; - using support::ErrorCategory; - - static std::mt19937 rng{std::random_device{}()}; - // TODO(REFACTOR): inject RNG via a Strategy/adapter so simulator is - // deterministic under test and replaceable by other random sources. - - int QasmSimulator::allocateQubit() { - // Grow the state by a factor of two, keeping existing amplitudes - // in the |...0> subspace and zeroing the |...1> subspace. - int index = m_qubits++; - if (index >= static_cast(m_measured.size())) - m_measured.resize(index + 1, false); - else - m_measured[index] = false; - std::vector> newState(m_state.size() * 2); - for (size_t i = 0; i < m_state.size(); ++i) { - newState[i] = m_state[i]; - newState[i + m_state.size()] = 0; +using support::BlochError; +using support::ErrorCategory; + +static std::mt19937 rng{std::random_device{}()}; +// TODO(REFACTOR): inject RNG via a Strategy/adapter so simulator is +// deterministic under test and replaceable by other random sources. + +int QasmSimulator::allocateQubit() { + // Grow the state by a factor of two, keeping existing amplitudes + // in the |...0> subspace and zeroing the |...1> subspace. + int index = m_qubits++; + if (index >= static_cast(m_measured.size())) + m_measured.resize(index + 1, false); + else + m_measured[index] = false; + std::vector> newState(m_state.size() * 2); + for (size_t i = 0; i < m_state.size(); ++i) { + newState[i] = m_state[i]; + newState[i + m_state.size()] = 0; + } + m_state.swap(newState); + return index; +} + +// REFACTOR: Consider a small Instruction/Gate registry (Command pattern) +// so gate matrices + logging strings live in data tables instead of one +// function per gate; would shrink interface and simplify adding new ops. +void QasmSimulator::applySingleQubitGate(int q, const std::array, 4>& m) { + ensureQubitActive(q); + // Standard blocked application over basis pairs differing at bit q. + size_t step = size_t{1} << q; + size_t size = m_state.size(); + for (size_t i = 0; i < size; i += 2 * step) { + for (size_t j = 0; j < step; ++j) { + size_t idx0 = i + j; + size_t idx1 = idx0 + step; + auto a0 = m_state[idx0]; + auto a1 = m_state[idx1]; + m_state[idx0] = m[0] * a0 + m[1] * a1; + m_state[idx1] = m[2] * a0 + m[3] * a1; } - m_state.swap(newState); - return index; } - - // REFACTOR: Consider a small Instruction/Gate registry (Command pattern) - // so gate matrices + logging strings live in data tables instead of one - // function per gate; would shrink interface and simplify adding new ops. - void QasmSimulator::applySingleQubitGate(int q, const std::array, 4>& m) { - ensureQubitActive(q); - // Standard blocked application over basis pairs differing at bit q. - size_t step = size_t{1} << q; - size_t size = m_state.size(); - for (size_t i = 0; i < size; i += 2 * step) { - for (size_t j = 0; j < step; ++j) { - size_t idx0 = i + j; - size_t idx1 = idx0 + step; - auto a0 = m_state[idx0]; - auto a1 = m_state[idx1]; - m_state[idx0] = m[0] * a0 + m[1] * a1; - m_state[idx1] = m[2] * a0 + m[3] * a1; +} + +void QasmSimulator::h(int q) { + const std::array, 4> m{1 / std::sqrt(2.0), 1 / std::sqrt(2.0), + 1 / std::sqrt(2.0), -1 / std::sqrt(2.0)}; + applySingleQubitGate(q, m); + if (m_logOps) + m_ops.emplace_back("h q[" + std::to_string(q) + "];\n"); +} + +void QasmSimulator::x(int q) { + const std::array, 4> m{0, 1, 1, 0}; + applySingleQubitGate(q, m); + if (m_logOps) + m_ops.emplace_back("x q[" + std::to_string(q) + "];\n"); +} + +void QasmSimulator::y(int q) { + const std::array, 4> m{0.0, std::complex(0, -1), + std::complex(0, 1), 0.0}; + applySingleQubitGate(q, m); + if (m_logOps) + m_ops.emplace_back("y q[" + std::to_string(q) + "];\n"); +} + +void QasmSimulator::z(int q) { + const std::array, 4> m{1.0, 0.0, 0.0, -1.0}; + applySingleQubitGate(q, m); + if (m_logOps) + m_ops.emplace_back("z q[" + std::to_string(q) + "];\n"); +} + +void QasmSimulator::rx(int q, double t) { + double ct = std::cos(t / 2); + double st = std::sin(t / 2); + const std::array, 4> m{ct, std::complex(0, -st), + std::complex(0, -st), ct}; + applySingleQubitGate(q, m); + if (m_logOps) + m_ops.emplace_back("rx(" + std::to_string(t) + ") q[" + std::to_string(q) + "];\n"); +} + +void QasmSimulator::ry(int q, double t) { + double ct = std::cos(t / 2); + double st = std::sin(t / 2); + const std::array, 4> m{ct, -st, st, ct}; + applySingleQubitGate(q, m); + if (m_logOps) + m_ops.emplace_back("ry(" + std::to_string(t) + ") q[" + std::to_string(q) + "];\n"); +} + +void QasmSimulator::rz(int q, double t) { + std::complex epos = std::exp(std::complex(0, -t / 2)); + std::complex eneg = std::exp(std::complex(0, t / 2)); + const std::array, 4> m{epos, 0.0, 0.0, eneg}; + applySingleQubitGate(q, m); + if (m_logOps) + m_ops.emplace_back("rz(" + std::to_string(t) + ") q[" + std::to_string(q) + "];\n"); +} + +void QasmSimulator::cx(int control, int target) { + ensureQubitActive(control); + ensureQubitActive(target); + // Swap amplitudes where control is 1 and target is 0 to flip target, + // iterating only the affected subspace to avoid per-index branching. + int low = std::min(control, target); + int high = std::max(control, target); + size_t lowBit = size_t{1} << low; + size_t highBit = size_t{1} << high; + size_t blockSize = size_t{1} << (high + 1); // chunk where bits above 'high' are fixed + size_t lowSpan = lowBit; // combinations for bits below 'low' + size_t betweenSpan = (high > low + 1) ? (size_t{1} << (high - low - 1)) : size_t{1}; + bool controlIsLow = control == low; + + for (size_t block = 0; block < m_state.size(); block += blockSize) { + for (size_t between = 0; between < betweenSpan; ++between) { + size_t mid = between << (low + 1); // bits between low and high + for (size_t lowOffset = 0; lowOffset < lowSpan; ++lowOffset) { + size_t base = block | mid | lowOffset; // control/target bits currently 0 + size_t idx0 = controlIsLow ? (base | lowBit) : (base | highBit); + size_t idx1 = controlIsLow ? (idx0 | highBit) : (idx0 | lowBit); + std::swap(m_state[idx0], m_state[idx1]); } } } - - void QasmSimulator::h(int q) { - const std::array, 4> m{1 / std::sqrt(2.0), 1 / std::sqrt(2.0), - 1 / std::sqrt(2.0), -1 / std::sqrt(2.0)}; - applySingleQubitGate(q, m); - if (m_logOps) - m_ops.emplace_back("h q[" + std::to_string(q) + "];\n"); + if (m_logOps) + m_ops.emplace_back("cx q[" + std::to_string(control) + "],q[" + std::to_string(target) + + "];\n"); +} + +void QasmSimulator::reset(int q) { + if (q < 0 || q >= m_qubits) { + throw BlochError(ErrorCategory::Runtime, 0, 0, + "qubit index " + std::to_string(q) + " is out of range"); } - - void QasmSimulator::x(int q) { - const std::array, 4> m{0, 1, 1, 0}; - applySingleQubitGate(q, m); - if (m_logOps) - m_ops.emplace_back("x q[" + std::to_string(q) + "];\n"); + if (q >= 0 && q < static_cast(m_measured.size())) + m_measured[q] = false; + // Put qubit q into |0>. + // If the state already has amplitude in the |...0> subspace, zero the |...1> subspace + // and renormalize. If all amplitude is in |...1>, deterministically move it into + // the |...0> subspace (equivalent to an X on a measured |1>), avoiding NaNs. + size_t bit = size_t{1} << q; + double norm0 = 0.0; + for (size_t i = 0; i < m_state.size(); ++i) { + if (!(i & bit)) + norm0 += std::norm(m_state[i]); } - void QasmSimulator::y(int q) { - const std::array, 4> m{0.0, std::complex(0, -1), - std::complex(0, 1), 0.0}; - applySingleQubitGate(q, m); - if (m_logOps) - m_ops.emplace_back("y q[" + std::to_string(q) + "];\n"); - } - - void QasmSimulator::z(int q) { - const std::array, 4> m{1.0, 0.0, 0.0, -1.0}; - applySingleQubitGate(q, m); - if (m_logOps) - m_ops.emplace_back("z q[" + std::to_string(q) + "];\n"); - } - - void QasmSimulator::rx(int q, double t) { - double ct = std::cos(t / 2); - double st = std::sin(t / 2); - const std::array, 4> m{ct, std::complex(0, -st), - std::complex(0, -st), ct}; - applySingleQubitGate(q, m); - if (m_logOps) - m_ops.emplace_back("rx(" + std::to_string(t) + ") q[" + std::to_string(q) + "];\n"); - } - - void QasmSimulator::ry(int q, double t) { - double ct = std::cos(t / 2); - double st = std::sin(t / 2); - const std::array, 4> m{ct, -st, st, ct}; - applySingleQubitGate(q, m); - if (m_logOps) - m_ops.emplace_back("ry(" + std::to_string(t) + ") q[" + std::to_string(q) + "];\n"); - } - - void QasmSimulator::rz(int q, double t) { - std::complex epos = std::exp(std::complex(0, -t / 2)); - std::complex eneg = std::exp(std::complex(0, t / 2)); - const std::array, 4> m{epos, 0.0, 0.0, eneg}; - applySingleQubitGate(q, m); - if (m_logOps) - m_ops.emplace_back("rz(" + std::to_string(t) + ") q[" + std::to_string(q) + "];\n"); - } - - void QasmSimulator::cx(int control, int target) { - ensureQubitActive(control); - ensureQubitActive(target); - // Swap amplitudes where control is 1 and target is 0 to flip target, - // iterating only the affected subspace to avoid per-index branching. - int low = std::min(control, target); - int high = std::max(control, target); - size_t lowBit = size_t{1} << low; - size_t highBit = size_t{1} << high; - size_t blockSize = size_t{1} << (high + 1); // chunk where bits above 'high' are fixed - size_t lowSpan = lowBit; // combinations for bits below 'low' - size_t betweenSpan = (high > low + 1) ? (size_t{1} << (high - low - 1)) : size_t{1}; - bool controlIsLow = control == low; - - for (size_t block = 0; block < m_state.size(); block += blockSize) { - for (size_t between = 0; between < betweenSpan; ++between) { - size_t mid = between << (low + 1); // bits between low and high - for (size_t lowOffset = 0; lowOffset < lowSpan; ++lowOffset) { - size_t base = block | mid | lowOffset; // control/target bits currently 0 - size_t idx0 = controlIsLow ? (base | lowBit) : (base | highBit); - size_t idx1 = controlIsLow ? (idx0 | highBit) : (idx0 | lowBit); - std::swap(m_state[idx0], m_state[idx1]); - } + if (norm0 == 0.0) { + // All amplitude is in the |...1> subspace: swap it into |...0>. + for (size_t i = 0; i < m_state.size(); ++i) { + if (i & bit) { + size_t j = i ^ bit; // flip target bit to 0 + m_state[j] = m_state[i]; + m_state[i] = 0.0; } } - if (m_logOps) - m_ops.emplace_back("cx q[" + std::to_string(control) + "],q[" + std::to_string(target) + - "];\n"); - } - - void QasmSimulator::reset(int q) { - if (q < 0 || q >= m_qubits) { - throw BlochError(ErrorCategory::Runtime, 0, 0, - "qubit index " + std::to_string(q) + " is out of range"); - } - if (q >= 0 && q < static_cast(m_measured.size())) - m_measured[q] = false; - // Put qubit q into |0>. - // If the state already has amplitude in the |...0> subspace, zero the |...1> subspace - // and renormalize. If all amplitude is in |...1>, deterministically move it into - // the |...0> subspace (equivalent to an X on a measured |1>), avoiding NaNs. - size_t bit = size_t{1} << q; - double norm0 = 0.0; + } else { + // Zero |...1> and renormalize |...0> + double inv = 1.0 / std::sqrt(norm0); for (size_t i = 0; i < m_state.size(); ++i) { - if (!(i & bit)) - norm0 += std::norm(m_state[i]); - } - - if (norm0 == 0.0) { - // All amplitude is in the |...1> subspace: swap it into |...0>. - for (size_t i = 0; i < m_state.size(); ++i) { - if (i & bit) { - size_t j = i ^ bit; // flip target bit to 0 - m_state[j] = m_state[i]; - m_state[i] = 0.0; - } - } - } else { - // Zero |...1> and renormalize |...0> - double inv = 1.0 / std::sqrt(norm0); - for (size_t i = 0; i < m_state.size(); ++i) { - if (i & bit) { - m_state[i] = 0.0; - } else { - m_state[i] *= inv; - } + if (i & bit) { + m_state[i] = 0.0; + } else { + m_state[i] *= inv; } } - - if (m_logOps) - m_ops.emplace_back("reset q[" + std::to_string(q) + "];\n"); } - int QasmSimulator::measure(int q) { - ensureQubitActive(q); - // Compute probability of |1>, sample, and collapse the state accordingly. - size_t bit = size_t{1} << q; - double p1 = 0; - for (size_t i = 0; i < m_state.size(); ++i) - if (i & bit) - p1 += std::norm(m_state[i]); - std::uniform_real_distribution dist(0.0, 1.0); - double r = dist(rng); - int res = r < p1 ? 1 : 0; - double norm = std::sqrt(res ? p1 : 1 - p1); - for (size_t i = 0; i < m_state.size(); ++i) { - if (((i & bit) ? 1 : 0) != res) - m_state[i] = 0; - else - m_state[i] /= norm; - } - if (m_logOps) - m_ops.emplace_back("measure q[" + std::to_string(q) + "] -> c[" + std::to_string(q) + - "];\n"); - if (q >= 0 && q < static_cast(m_measured.size())) - m_measured[q] = true; - return res; + if (m_logOps) + m_ops.emplace_back("reset q[" + std::to_string(q) + "];\n"); +} + +int QasmSimulator::measure(int q) { + ensureQubitActive(q); + // Compute probability of |1>, sample, and collapse the state accordingly. + size_t bit = size_t{1} << q; + double p1 = 0; + for (size_t i = 0; i < m_state.size(); ++i) + if (i & bit) + p1 += std::norm(m_state[i]); + std::uniform_real_distribution dist(0.0, 1.0); + double r = dist(rng); + int res = r < p1 ? 1 : 0; + double norm = std::sqrt(res ? p1 : 1 - p1); + for (size_t i = 0; i < m_state.size(); ++i) { + if (((i & bit) ? 1 : 0) != res) + m_state[i] = 0; + else + m_state[i] /= norm; } - - std::string QasmSimulator::getQasm() const { - const std::string header = "OPENQASM 2.0;\ninclude \"qelib1.inc\";\n"; - const std::string qreg = "qreg q[" + std::to_string(m_qubits) + "];\n"; - const std::string creg = "creg c[" + std::to_string(m_qubits) + "];\n"; - size_t total = header.size() + qreg.size() + creg.size(); - for (const auto& op : m_ops) total += op.size(); - std::string out; - out.reserve(total); - out.append(header); - out.append(qreg); - out.append(creg); - for (const auto& op : m_ops) out.append(op); - return out; + if (m_logOps) + m_ops.emplace_back("measure q[" + std::to_string(q) + "] -> c[" + std::to_string(q) + + "];\n"); + if (q >= 0 && q < static_cast(m_measured.size())) + m_measured[q] = true; + return res; +} + +std::string QasmSimulator::getQasm() const { + const std::string header = "OPENQASM 2.0;\ninclude \"qelib1.inc\";\n"; + const std::string qreg = "qreg q[" + std::to_string(m_qubits) + "];\n"; + const std::string creg = "creg c[" + std::to_string(m_qubits) + "];\n"; + size_t total = header.size() + qreg.size() + creg.size(); + for (const auto& op : m_ops) + total += op.size(); + std::string out; + out.reserve(total); + out.append(header); + out.append(qreg); + out.append(creg); + for (const auto& op : m_ops) + out.append(op); + return out; +} + +void QasmSimulator::ensureQubitActive(int q) const { + if (q < 0 || q >= m_qubits) { + throw BlochError(ErrorCategory::Runtime, 0, 0, + "qubit index " + std::to_string(q) + " is out of range"); } - - void QasmSimulator::ensureQubitActive(int q) const { - if (q < 0 || q >= m_qubits) { - throw BlochError(ErrorCategory::Runtime, 0, 0, - "qubit index " + std::to_string(q) + " is out of range"); - } - if (q < static_cast(m_measured.size()) && m_measured[q]) { - throw BlochError(ErrorCategory::Runtime, 0, 0, - "cannot operate on measured qubit q[" + std::to_string(q) + "]"); - } + if (q < static_cast(m_measured.size()) && m_measured[q]) { + throw BlochError(ErrorCategory::Runtime, 0, 0, + "cannot operate on measured qubit q[" + std::to_string(q) + "]"); } +} } // namespace bloch::runtime diff --git a/src/bloch/runtime/qasm_simulator.hpp b/src/bloch/runtime/qasm_simulator.hpp index 586db62..9664119 100644 --- a/src/bloch/runtime/qasm_simulator.hpp +++ b/src/bloch/runtime/qasm_simulator.hpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,39 +18,40 @@ #include #include #include + #include "bloch/support/error/bloch_error.hpp" namespace bloch::runtime { - // An ideal statevector simulator with a QASM log. - // TODO: performance optimisation post 1.0.0 - class QasmSimulator { - public: - explicit QasmSimulator(bool logOps = true) : m_logOps(logOps) {} - int allocateQubit(); - void h(int q); - void x(int q); - void y(int q); - void z(int q); - void rx(int q, double theta); - void ry(int q, double theta); - void rz(int q, double theta); - void cx(int control, int target); - void reset(int q); - int measure(int q); - std::string getQasm() const; - size_t stateSize() const { return m_state.size(); } - - private: - int m_qubits = 0; - std::vector> m_state{1}; - std::vector m_ops; - bool m_logOps = true; - std::vector m_measured; - - // Apply a 2x2 unitary to qubit q. - void applySingleQubitGate(int q, const std::array, 4>& m); - void ensureQubitActive(int q) const; - }; +// An ideal statevector simulator with a QASM log. +// TODO: performance optimisation post 1.0.0 +class QasmSimulator { + public: + explicit QasmSimulator(bool logOps = true) : m_logOps(logOps) {} + int allocateQubit(); + void h(int q); + void x(int q); + void y(int q); + void z(int q); + void rx(int q, double theta); + void ry(int q, double theta); + void rz(int q, double theta); + void cx(int control, int target); + void reset(int q); + int measure(int q); + std::string getQasm() const; + size_t stateSize() const { return m_state.size(); } + + private: + int m_qubits = 0; + std::vector> m_state{1}; + std::vector m_ops; + bool m_logOps = true; + std::vector m_measured; + + // Apply a 2x2 unitary to qubit q. + void applySingleQubitGate(int q, const std::array, 4>& m); + void ensureQubitActive(int q) const; +}; } // namespace bloch::runtime diff --git a/src/bloch/runtime/runtime_evaluator.cpp b/src/bloch/runtime/runtime_evaluator.cpp index cf6f844..5e4af24 100644 --- a/src/bloch/runtime/runtime_evaluator.cpp +++ b/src/bloch/runtime/runtime_evaluator.cpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -31,1037 +31,912 @@ namespace bloch::runtime { - using compiler::builtInGates; - using support::BlochError; - using support::blochWarning; - using support::ErrorCategory; - - namespace { - std::string typeKey(const RuntimeTypeInfo& t); - std::unique_ptr runtimeTypeToAst(const RuntimeTypeInfo& rt); - RuntimeTypeInfo typeInfoFromValue(const Value& v); +using compiler::builtInGates; +using support::BlochError; +using support::blochWarning; +using support::ErrorCategory; + +namespace { +std::string typeKey(const RuntimeTypeInfo& t); +std::unique_ptr runtimeTypeToAst(const RuntimeTypeInfo& rt); +RuntimeTypeInfo typeInfoFromValue(const Value& v); +} // namespace + +static constexpr bool kTraceConstructors = false; + +static std::pair findStaticFieldWithOwner(RuntimeClass* cls, + const std::string& name) { + RuntimeClass* cur = cls; + while (cur) { + auto fit = cur->staticFieldIndex.find(name); + if (fit != cur->staticFieldIndex.end()) + return {&cur->staticFields[fit->second], cur}; + cur = cur->base; } - - static constexpr bool kTraceConstructors = false; - - static std::pair findStaticFieldWithOwner( - RuntimeClass* cls, const std::string& name) { - RuntimeClass* cur = cls; - while (cur) { - auto fit = cur->staticFieldIndex.find(name); - if (fit != cur->staticFieldIndex.end()) - return {&cur->staticFields[fit->second], cur}; - cur = cur->base; + return {nullptr, nullptr}; +} + +static bool isNullReference(const Value& v) { + return v.type == Value::Type::Object && !v.objectValue; +} + +static std::string valueToString(const Value& v) { + // Pretty-print a runtime value for echo and tracked summaries. + std::ostringstream oss; + switch (v.type) { + case Value::Type::String: + return v.stringValue; + case Value::Type::Char: { + oss << "'" << v.charValue << "'"; + return oss.str(); } - return {nullptr, nullptr}; - } - - static bool isNullReference(const Value& v) { - return v.type == Value::Type::Object && !v.objectValue; - } - - static std::string valueToString(const Value& v) { - // Pretty-print a runtime value for echo and tracked summaries. - std::ostringstream oss; - switch (v.type) { - case Value::Type::String: - return v.stringValue; - case Value::Type::Char: { - oss << "'" << v.charValue << "'"; - return oss.str(); - } - case Value::Type::Float: { - // Show a trailing .0 for whole-number floats - if (std::isfinite(v.floatValue) && std::floor(v.floatValue) == v.floatValue) { - oss.setf(std::ios::fixed); - oss << std::setprecision(1) << v.floatValue; - } else { - oss << v.floatValue; - } - return oss.str(); + case Value::Type::Float: { + // Show a trailing .0 for whole-number floats + if (std::isfinite(v.floatValue) && std::floor(v.floatValue) == v.floatValue) { + oss.setf(std::ios::fixed); + oss << std::setprecision(1) << v.floatValue; + } else { + oss << v.floatValue; } - case Value::Type::Bit: - return std::to_string(v.bitValue); - case Value::Type::Boolean: - return v.boolValue ? "true" : "false"; - case Value::Type::Int: - return std::to_string(v.intValue); - case Value::Type::Long: - return std::to_string(static_cast(v.longValue)); - case Value::Type::BitArray: - oss << "{"; - for (size_t i = 0; i < v.bitArray.size(); ++i) { - if (i) - oss << ", "; - oss << v.bitArray[i]; - } - oss << "}"; - return oss.str(); - case Value::Type::BooleanArray: - oss << "{"; - for (size_t i = 0; i < v.boolArray.size(); ++i) { - if (i) - oss << ", "; - oss << (v.boolArray[i] ? "true" : "false"); - } - oss << "}"; - return oss.str(); - case Value::Type::IntArray: - oss << "{"; - for (size_t i = 0; i < v.intArray.size(); ++i) { - if (i) - oss << ", "; - oss << v.intArray[i]; - } - oss << "}"; - return oss.str(); - case Value::Type::LongArray: - oss << "{"; - for (size_t i = 0; i < v.longArray.size(); ++i) { - if (i) - oss << ", "; - oss << v.longArray[i]; - } - oss << "}"; - return oss.str(); - case Value::Type::FloatArray: - oss << "{"; - for (size_t i = 0; i < v.floatArray.size(); ++i) { - if (i) - oss << ", "; - oss << v.floatArray[i]; - } - oss << "}"; - return oss.str(); - case Value::Type::StringArray: - oss << "{"; - for (size_t i = 0; i < v.stringArray.size(); ++i) { - if (i) - oss << ", "; - oss << v.stringArray[i]; - } - oss << "}"; - return oss.str(); - case Value::Type::CharArray: - oss << "{"; - for (size_t i = 0; i < v.charArray.size(); ++i) { - if (i) - oss << ", "; - oss << "'" << v.charArray[i] << "'"; - } - oss << "}"; - return oss.str(); - case Value::Type::Object: - if (isNullReference(v)) - return "null"; - if (v.objectValue && v.objectValue->cls) - return "<" + v.objectValue->cls->name + " object>"; - return ""; - case Value::Type::ObjectArray: - oss << "{"; - for (size_t i = 0; i < v.objectArray.size(); ++i) { - if (i) - oss << ", "; - auto& obj = v.objectArray[i]; - if (obj && obj->cls) - oss << "<" << obj->cls->name << ">"; - else - oss << "null"; - } - oss << "}"; - return oss.str(); - case Value::Type::ClassRef: - return ""; - default: - return ""; + return oss.str(); } - } - - RuntimeTypeInfo RuntimeEvaluator::typeInfoFromAst( - Type* type, const std::unordered_map& subst) const { - RuntimeTypeInfo info; - if (!type) - return info; - if (auto prim = dynamic_cast(type)) { - if (prim->name == "int") - info.kind = Value::Type::Int; - else if (prim->name == "long") - info.kind = Value::Type::Long; - else if (prim->name == "float") - info.kind = Value::Type::Float; - else if (prim->name == "bit") - info.kind = Value::Type::Bit; - else if (prim->name == "boolean") - info.kind = Value::Type::Boolean; - else if (prim->name == "string") - info.kind = Value::Type::String; - else if (prim->name == "char") - info.kind = Value::Type::Char; - else if (prim->name == "qubit") - info.kind = Value::Type::Qubit; - } else if (auto named = dynamic_cast(type)) { - // Type parameter substitution - if (!named->nameParts.empty()) { - std::string base = named->nameParts.back(); - auto it = subst.find(base); - if (it != subst.end()) - return it->second; - info.kind = Value::Type::Object; - info.className = base; - for (auto& arg : named->typeArguments) - info.typeArgs.push_back(typeInfoFromAst(arg.get(), subst)); - info.className = typeKey(info); - // Strip to base if no args (non-generic class) - if (info.typeArgs.empty()) - info.className = base; - } - } else if (auto arr = dynamic_cast(type)) { - auto elem = typeInfoFromAst(arr->elementType.get(), subst); - switch (elem.kind) { - case Value::Type::Int: - info.kind = Value::Type::IntArray; - break; - case Value::Type::Long: - info.kind = Value::Type::LongArray; - break; - case Value::Type::Float: - info.kind = Value::Type::FloatArray; - break; - case Value::Type::Bit: - info.kind = Value::Type::BitArray; - break; - case Value::Type::Boolean: - info.kind = Value::Type::BooleanArray; - break; - case Value::Type::String: - info.kind = Value::Type::StringArray; - break; - case Value::Type::Char: - info.kind = Value::Type::CharArray; - break; - case Value::Type::Qubit: - info.kind = Value::Type::QubitArray; - break; - default: - info.kind = Value::Type::ObjectArray; - info.className = elem.className; - info.typeArgs.push_back(elem); - break; + case Value::Type::Bit: + return std::to_string(v.bitValue); + case Value::Type::Boolean: + return v.boolValue ? "true" : "false"; + case Value::Type::Int: + return std::to_string(v.intValue); + case Value::Type::Long: + return std::to_string(static_cast(v.longValue)); + case Value::Type::BitArray: + oss << "{"; + for (size_t i = 0; i < v.bitArray.size(); ++i) { + if (i) + oss << ", "; + oss << v.bitArray[i]; + } + oss << "}"; + return oss.str(); + case Value::Type::BooleanArray: + oss << "{"; + for (size_t i = 0; i < v.boolArray.size(); ++i) { + if (i) + oss << ", "; + oss << (v.boolArray[i] ? "true" : "false"); + } + oss << "}"; + return oss.str(); + case Value::Type::IntArray: + oss << "{"; + for (size_t i = 0; i < v.intArray.size(); ++i) { + if (i) + oss << ", "; + oss << v.intArray[i]; + } + oss << "}"; + return oss.str(); + case Value::Type::LongArray: + oss << "{"; + for (size_t i = 0; i < v.longArray.size(); ++i) { + if (i) + oss << ", "; + oss << v.longArray[i]; + } + oss << "}"; + return oss.str(); + case Value::Type::FloatArray: + oss << "{"; + for (size_t i = 0; i < v.floatArray.size(); ++i) { + if (i) + oss << ", "; + oss << v.floatArray[i]; + } + oss << "}"; + return oss.str(); + case Value::Type::StringArray: + oss << "{"; + for (size_t i = 0; i < v.stringArray.size(); ++i) { + if (i) + oss << ", "; + oss << v.stringArray[i]; + } + oss << "}"; + return oss.str(); + case Value::Type::CharArray: + oss << "{"; + for (size_t i = 0; i < v.charArray.size(); ++i) { + if (i) + oss << ", "; + oss << "'" << v.charArray[i] << "'"; + } + oss << "}"; + return oss.str(); + case Value::Type::Object: + if (isNullReference(v)) + return "null"; + if (v.objectValue && v.objectValue->cls) + return "<" + v.objectValue->cls->name + " object>"; + return ""; + case Value::Type::ObjectArray: + oss << "{"; + for (size_t i = 0; i < v.objectArray.size(); ++i) { + if (i) + oss << ", "; + auto& obj = v.objectArray[i]; + if (obj && obj->cls) + oss << "<" << obj->cls->name << ">"; + else + oss << "null"; } - } else if (dynamic_cast(type)) { - info.kind = Value::Type::Void; - } - return info; + oss << "}"; + return oss.str(); + case Value::Type::ClassRef: + return ""; + default: + return ""; } +} - namespace { - std::string typeKey(const RuntimeTypeInfo& t) { - if (!t.className.empty()) { - if (t.typeArgs.empty()) - return t.className; - std::ostringstream oss; - oss << t.className; - // If className already includes args (e.g. from nesting), avoid duplication. - if (t.className.find('<') == std::string::npos) { - oss << "<"; - for (size_t i = 0; i < t.typeArgs.size(); ++i) { - if (i) - oss << ","; - oss << typeKey(t.typeArgs[i]); - } - oss << ">"; - } - return oss.str(); - } - // Primitive / array labels - switch (t.kind) { - case Value::Type::Int: - return "int"; - case Value::Type::Long: - return "long"; - case Value::Type::Float: - return "float"; - case Value::Type::Bit: - return "bit"; - case Value::Type::Boolean: - return "boolean"; - case Value::Type::String: - return "string"; - case Value::Type::Char: - return "char"; - case Value::Type::Qubit: - return "qubit"; - case Value::Type::IntArray: - return "int[]"; - case Value::Type::LongArray: - return "long[]"; - case Value::Type::FloatArray: - return "float[]"; - case Value::Type::BitArray: - return "bit[]"; - case Value::Type::BooleanArray: - return "boolean[]"; - case Value::Type::StringArray: - return "string[]"; - case Value::Type::CharArray: - return "char[]"; - case Value::Type::QubitArray: - return "qubit[]"; - case Value::Type::ObjectArray: - if (!t.typeArgs.empty()) - return typeKey(t.typeArgs.front()) + "[]"; - if (!t.className.empty()) - return t.className + "[]"; - return "object[]"; - default: - return "unknown"; - } - } - } // namespace - - namespace { - std::unique_ptr runtimeTypeToAst(const RuntimeTypeInfo& rt) { - if (!rt.className.empty()) { - auto nt = std::make_unique(std::vector{rt.className}); - for (const auto& ta : rt.typeArgs) - nt->typeArguments.push_back(runtimeTypeToAst(ta)); - return nt; - } - switch (rt.kind) { - case Value::Type::Int: - return std::make_unique("int"); - case Value::Type::Long: - return std::make_unique("long"); - case Value::Type::Float: - return std::make_unique("float"); - case Value::Type::Bit: - return std::make_unique("bit"); - case Value::Type::Boolean: - return std::make_unique("boolean"); - case Value::Type::String: - return std::make_unique("string"); - case Value::Type::Char: - return std::make_unique("char"); - case Value::Type::Qubit: - return std::make_unique("qubit"); - case Value::Type::IntArray: - return std::make_unique(std::make_unique("int"), -1, - nullptr); - case Value::Type::LongArray: - return std::make_unique(std::make_unique("long"), -1, - nullptr); - case Value::Type::FloatArray: - return std::make_unique(std::make_unique("float"), -1, - nullptr); - case Value::Type::BitArray: - return std::make_unique(std::make_unique("bit"), -1, - nullptr); - case Value::Type::BooleanArray: - return std::make_unique(std::make_unique("boolean"), - -1, nullptr); - case Value::Type::StringArray: - return std::make_unique(std::make_unique("string"), - -1, nullptr); - case Value::Type::CharArray: - return std::make_unique(std::make_unique("char"), -1, - nullptr); - case Value::Type::ObjectArray: - return std::make_unique(!rt.typeArgs.empty() - ? runtimeTypeToAst(rt.typeArgs.front()) - : std::make_unique("int"), - -1, nullptr); - default: - return std::make_unique(); - } - } - - RuntimeTypeInfo typeInfoFromValue(const Value& v) { - RuntimeTypeInfo t; - switch (v.type) { - case Value::Type::Int: - t.kind = Value::Type::Int; - break; - case Value::Type::Long: - t.kind = Value::Type::Long; - break; - case Value::Type::Float: - t.kind = Value::Type::Float; - break; - case Value::Type::Bit: - t.kind = Value::Type::Bit; - break; - case Value::Type::Boolean: - t.kind = Value::Type::Boolean; - break; - case Value::Type::String: - t.kind = Value::Type::String; - break; - case Value::Type::Char: - t.kind = Value::Type::Char; - break; - case Value::Type::Qubit: - t.kind = Value::Type::Qubit; - break; - case Value::Type::Object: - t.kind = Value::Type::Object; - if (!v.className.empty()) - t.className = v.className; - else if (v.objectValue && v.objectValue->cls) - t.className = v.objectValue->cls->name; - break; - case Value::Type::ObjectArray: - t.kind = Value::Type::ObjectArray; - if (!v.className.empty()) - t.className = v.className; - break; - case Value::Type::LongArray: - t.kind = Value::Type::LongArray; - break; - default: - t.kind = v.type; - break; - } - return t; +RuntimeTypeInfo RuntimeEvaluator::typeInfoFromAst( + Type* type, const std::unordered_map& subst) const { + RuntimeTypeInfo info; + if (!type) + return info; + if (auto prim = dynamic_cast(type)) { + if (prim->name == "int") + info.kind = Value::Type::Int; + else if (prim->name == "long") + info.kind = Value::Type::Long; + else if (prim->name == "float") + info.kind = Value::Type::Float; + else if (prim->name == "bit") + info.kind = Value::Type::Bit; + else if (prim->name == "boolean") + info.kind = Value::Type::Boolean; + else if (prim->name == "string") + info.kind = Value::Type::String; + else if (prim->name == "char") + info.kind = Value::Type::Char; + else if (prim->name == "qubit") + info.kind = Value::Type::Qubit; + } else if (auto named = dynamic_cast(type)) { + // Type parameter substitution + if (!named->nameParts.empty()) { + std::string base = named->nameParts.back(); + auto it = subst.find(base); + if (it != subst.end()) + return it->second; + info.kind = Value::Type::Object; + info.className = base; + for (auto& arg : named->typeArguments) + info.typeArgs.push_back(typeInfoFromAst(arg.get(), subst)); + info.className = typeKey(info); + // Strip to base if no args (non-generic class) + if (info.typeArgs.empty()) + info.className = base; } - } // namespace - - RuntimeTypeInfo RuntimeEvaluator::typeInfoFromAst(Type* type) const { - static const std::unordered_map emptySubst; - return typeInfoFromAst(type, emptySubst); - } - - Value RuntimeEvaluator::defaultValueForField(const RuntimeField& field, - const std::string& ownerLabel) { - Value v; - v.type = field.type.kind; - auto makeQubitName = [&](int index) { - std::ostringstream oss; - oss << ownerLabel << "." << field.name; - if (index >= 0) - oss << "[" << index << "]"; - return oss.str(); - }; - switch (field.type.kind) { + } else if (auto arr = dynamic_cast(type)) { + auto elem = typeInfoFromAst(arr->elementType.get(), subst); + switch (elem.kind) { case Value::Type::Int: - v.intValue = 0; + info.kind = Value::Type::IntArray; break; case Value::Type::Long: - v.longValue = 0; + info.kind = Value::Type::LongArray; break; case Value::Type::Float: - v.floatValue = 0.0; + info.kind = Value::Type::FloatArray; break; case Value::Type::Bit: - v.bitValue = 0; + info.kind = Value::Type::BitArray; break; case Value::Type::Boolean: - v.boolValue = false; + info.kind = Value::Type::BooleanArray; break; case Value::Type::String: - v.stringValue = ""; + info.kind = Value::Type::StringArray; break; case Value::Type::Char: - v.charValue = '\0'; + info.kind = Value::Type::CharArray; break; case Value::Type::Qubit: - v.qubit = allocateTrackedQubit(makeQubitName(-1)); - break; - case Value::Type::IntArray: - v.intArray.assign(std::max(0, field.arraySize), 0); - break; - case Value::Type::LongArray: - v.longArray.assign(std::max(0, field.arraySize), 0); - break; - case Value::Type::FloatArray: - v.floatArray.assign(std::max(0, field.arraySize), 0.0); - break; - case Value::Type::BitArray: - v.bitArray.assign(std::max(0, field.arraySize), 0); - break; - case Value::Type::BooleanArray: - v.boolArray.assign(std::max(0, field.arraySize), false); - break; - case Value::Type::StringArray: - v.stringArray.assign(std::max(0, field.arraySize), ""); - break; - case Value::Type::CharArray: - v.charArray.assign(std::max(0, field.arraySize), '\0'); - break; - case Value::Type::QubitArray: { - int n = std::max(0, field.arraySize); - v.qubitArray.resize(n); - for (int i = 0; i < n; ++i) - v.qubitArray[i] = allocateTrackedQubit(makeQubitName(i)); - break; - } - case Value::Type::ObjectArray: { - int n = std::max(0, field.arraySize); - v.objectArray.assign(n, {}); + info.kind = Value::Type::QubitArray; break; - } - case Value::Type::Object: - case Value::Type::ClassRef: - case Value::Type::Void: default: + info.kind = Value::Type::ObjectArray; + info.className = elem.className; + info.typeArgs.push_back(elem); break; } - v.className = field.type.className; - return v; + } else if (dynamic_cast(type)) { + info.kind = Value::Type::Void; } - - void RuntimeEvaluator::execute(Program& program) { - if (m_executed) { - throw BlochError(ErrorCategory::Runtime, 0, 0, - "RuntimeEvaluator is single-use; construct a new instance per run"); - } - m_executed = true; - m_functions.clear(); - m_env.clear(); - m_measurements.clear(); - m_trackedCounts.clear(); - m_echoBuffer.clear(); - m_qubits.clear(); - m_lastMeasurement.clear(); - m_returnValue = {}; - m_hasReturn = false; - m_classTable.clear(); - m_heap.clear(); - m_currentClassCtx = nullptr; - m_inStaticContext = false; - m_inConstructor = false; - m_inDestructor = false; - m_stopGc = false; - m_gcRequested = false; - m_gcThreadStarted = false; - m_allocSinceGc = 0; - m_deferredRuntimeError = nullptr; - m_sim = QasmSimulator{m_collectQasmLog}; - bool hasClasses = !program.classes.empty(); - if (hasClasses) { - buildClassTable(program); - for (auto& kv : m_classTable) initStaticFields(kv.second.get()); - ensureGcThread(); - } - for (auto& fn : program.functions) { - m_functions[fn->name] = fn.get(); - } - auto it = m_functions.find("main"); - if (it != m_functions.end()) { - call(it->second, {}); - } - if (m_gcThreadStarted) { - m_stopGc = true; - m_gcRequested = true; - m_gcCv.notify_all(); - if (m_gcThread.joinable()) - m_gcThread.join(); + return info; +} + +namespace { +std::string typeKey(const RuntimeTypeInfo& t) { + if (!t.className.empty()) { + if (t.typeArgs.empty()) + return t.className; + std::ostringstream oss; + oss << t.className; + // If className already includes args (e.g. from nesting), avoid duplication. + if (t.className.find('<') == std::string::npos) { + oss << "<"; + for (size_t i = 0; i < t.typeArgs.size(); ++i) { + if (i) + oss << ","; + oss << typeKey(t.typeArgs[i]); + } + oss << ">"; } - runCycleCollector(); - throwDeferredRuntimeError(); - // Ensure warnings appear before any normal echo output - if (m_warnOnExit) - warnUnmeasured(); - flushEchoes(); + return oss.str(); } - - RuntimeEvaluator::~RuntimeEvaluator() { + // Primitive / array labels + switch (t.kind) { + case Value::Type::Int: + return "int"; + case Value::Type::Long: + return "long"; + case Value::Type::Float: + return "float"; + case Value::Type::Bit: + return "bit"; + case Value::Type::Boolean: + return "boolean"; + case Value::Type::String: + return "string"; + case Value::Type::Char: + return "char"; + case Value::Type::Qubit: + return "qubit"; + case Value::Type::IntArray: + return "int[]"; + case Value::Type::LongArray: + return "long[]"; + case Value::Type::FloatArray: + return "float[]"; + case Value::Type::BitArray: + return "bit[]"; + case Value::Type::BooleanArray: + return "boolean[]"; + case Value::Type::StringArray: + return "string[]"; + case Value::Type::CharArray: + return "char[]"; + case Value::Type::QubitArray: + return "qubit[]"; + case Value::Type::ObjectArray: + if (!t.typeArgs.empty()) + return typeKey(t.typeArgs.front()) + "[]"; + if (!t.className.empty()) + return t.className + "[]"; + return "object[]"; + default: + return "unknown"; + } +} +} // namespace + +namespace { +std::unique_ptr runtimeTypeToAst(const RuntimeTypeInfo& rt) { + if (!rt.className.empty()) { + auto nt = std::make_unique(std::vector{rt.className}); + for (const auto& ta : rt.typeArgs) + nt->typeArguments.push_back(runtimeTypeToAst(ta)); + return nt; + } + switch (rt.kind) { + case Value::Type::Int: + return std::make_unique("int"); + case Value::Type::Long: + return std::make_unique("long"); + case Value::Type::Float: + return std::make_unique("float"); + case Value::Type::Bit: + return std::make_unique("bit"); + case Value::Type::Boolean: + return std::make_unique("boolean"); + case Value::Type::String: + return std::make_unique("string"); + case Value::Type::Char: + return std::make_unique("char"); + case Value::Type::Qubit: + return std::make_unique("qubit"); + case Value::Type::IntArray: + return std::make_unique(std::make_unique("int"), -1, nullptr); + case Value::Type::LongArray: + return std::make_unique(std::make_unique("long"), -1, + nullptr); + case Value::Type::FloatArray: + return std::make_unique(std::make_unique("float"), -1, + nullptr); + case Value::Type::BitArray: + return std::make_unique(std::make_unique("bit"), -1, nullptr); + case Value::Type::BooleanArray: + return std::make_unique(std::make_unique("boolean"), -1, + nullptr); + case Value::Type::StringArray: + return std::make_unique(std::make_unique("string"), -1, + nullptr); + case Value::Type::CharArray: + return std::make_unique(std::make_unique("char"), -1, + nullptr); + case Value::Type::ObjectArray: + return std::make_unique(!rt.typeArgs.empty() + ? runtimeTypeToAst(rt.typeArgs.front()) + : std::make_unique("int"), + -1, nullptr); + default: + return std::make_unique(); + } +} + +RuntimeTypeInfo typeInfoFromValue(const Value& v) { + RuntimeTypeInfo t; + switch (v.type) { + case Value::Type::Int: + t.kind = Value::Type::Int; + break; + case Value::Type::Long: + t.kind = Value::Type::Long; + break; + case Value::Type::Float: + t.kind = Value::Type::Float; + break; + case Value::Type::Bit: + t.kind = Value::Type::Bit; + break; + case Value::Type::Boolean: + t.kind = Value::Type::Boolean; + break; + case Value::Type::String: + t.kind = Value::Type::String; + break; + case Value::Type::Char: + t.kind = Value::Type::Char; + break; + case Value::Type::Qubit: + t.kind = Value::Type::Qubit; + break; + case Value::Type::Object: + t.kind = Value::Type::Object; + if (!v.className.empty()) + t.className = v.className; + else if (v.objectValue && v.objectValue->cls) + t.className = v.objectValue->cls->name; + break; + case Value::Type::ObjectArray: + t.kind = Value::Type::ObjectArray; + if (!v.className.empty()) + t.className = v.className; + break; + case Value::Type::LongArray: + t.kind = Value::Type::LongArray; + break; + default: + t.kind = v.type; + break; + } + return t; +} +} // namespace + +RuntimeTypeInfo RuntimeEvaluator::typeInfoFromAst(Type* type) const { + static const std::unordered_map emptySubst; + return typeInfoFromAst(type, emptySubst); +} + +Value RuntimeEvaluator::defaultValueForField(const RuntimeField& field, + const std::string& ownerLabel) { + Value v; + v.type = field.type.kind; + auto makeQubitName = [&](int index) { + std::ostringstream oss; + oss << ownerLabel << "." << field.name; + if (index >= 0) + oss << "[" << index << "]"; + return oss.str(); + }; + switch (field.type.kind) { + case Value::Type::Int: + v.intValue = 0; + break; + case Value::Type::Long: + v.longValue = 0; + break; + case Value::Type::Float: + v.floatValue = 0.0; + break; + case Value::Type::Bit: + v.bitValue = 0; + break; + case Value::Type::Boolean: + v.boolValue = false; + break; + case Value::Type::String: + v.stringValue = ""; + break; + case Value::Type::Char: + v.charValue = '\0'; + break; + case Value::Type::Qubit: + v.qubit = allocateTrackedQubit(makeQubitName(-1)); + break; + case Value::Type::IntArray: + v.intArray.assign(std::max(0, field.arraySize), 0); + break; + case Value::Type::LongArray: + v.longArray.assign(std::max(0, field.arraySize), 0); + break; + case Value::Type::FloatArray: + v.floatArray.assign(std::max(0, field.arraySize), 0.0); + break; + case Value::Type::BitArray: + v.bitArray.assign(std::max(0, field.arraySize), 0); + break; + case Value::Type::BooleanArray: + v.boolArray.assign(std::max(0, field.arraySize), false); + break; + case Value::Type::StringArray: + v.stringArray.assign(std::max(0, field.arraySize), ""); + break; + case Value::Type::CharArray: + v.charArray.assign(std::max(0, field.arraySize), '\0'); + break; + case Value::Type::QubitArray: { + int n = std::max(0, field.arraySize); + v.qubitArray.resize(n); + for (int i = 0; i < n; ++i) + v.qubitArray[i] = allocateTrackedQubit(makeQubitName(i)); + break; + } + case Value::Type::ObjectArray: { + int n = std::max(0, field.arraySize); + v.objectArray.assign(n, {}); + break; + } + case Value::Type::Object: + case Value::Type::ClassRef: + case Value::Type::Void: + default: + break; + } + v.className = field.type.className; + return v; +} + +void RuntimeEvaluator::execute(Program& program) { + if (m_executed) { + throw BlochError(ErrorCategory::Runtime, 0, 0, + "RuntimeEvaluator is single-use; construct a new instance per run"); + } + m_executed = true; + m_functions.clear(); + m_env.clear(); + m_measurements.clear(); + m_trackedCounts.clear(); + m_echoBuffer.clear(); + m_qubits.clear(); + m_lastMeasurement.clear(); + m_returnValue = {}; + m_hasReturn = false; + m_classTable.clear(); + m_heap.clear(); + m_currentClassCtx = nullptr; + m_inStaticContext = false; + m_inConstructor = false; + m_inDestructor = false; + m_stopGc = false; + m_gcRequested = false; + m_gcThreadStarted = false; + m_allocSinceGc = 0; + m_deferredRuntimeError = nullptr; + m_sim = QasmSimulator{m_collectQasmLog}; + bool hasClasses = !program.classes.empty(); + if (hasClasses) { + buildClassTable(program); + for (auto& kv : m_classTable) + initStaticFields(kv.second.get()); + ensureGcThread(); + } + for (auto& fn : program.functions) { + m_functions[fn->name] = fn.get(); + } + auto it = m_functions.find("main"); + if (it != m_functions.end()) { + call(it->second, {}); + } + if (m_gcThreadStarted) { m_stopGc = true; + m_gcRequested = true; m_gcCv.notify_all(); if (m_gcThread.joinable()) m_gcThread.join(); } - - Value RuntimeEvaluator::lookup(const std::string& name) { - for (auto it = m_env.rbegin(); it != m_env.rend(); ++it) { - auto fit = it->find(name); - if (fit != it->end()) - return fit->second.value; - } - std::shared_ptr thisObj = currentThisObject(); - if (m_currentClassCtx) { - if (!m_inStaticContext && thisObj) { - RuntimeField* field = findInstanceField(m_currentClassCtx, name); - if (field && field->offset < thisObj->fields.size()) - return thisObj->fields[field->offset]; - } - auto [field, owner] = findStaticFieldWithOwner(m_currentClassCtx, name); - if (field && owner && field->offset < owner->staticStorage.size()) - return owner->staticStorage[field->offset]; - } - auto clsIt = m_classTable.find(name); - if (clsIt != m_classTable.end()) { - Value v; - v.type = Value::Type::ClassRef; - v.classRef = clsIt->second.get(); - v.className = name; - return v; - } - auto tmplIt = m_genericTemplates.find(name); - if (tmplIt != m_genericTemplates.end()) { - Value v; - v.type = Value::Type::ClassRef; - v.classRef = nullptr; - v.className = name; - return v; - } - return {}; + runCycleCollector(); + throwDeferredRuntimeError(); + // Ensure warnings appear before any normal echo output + if (m_warnOnExit) + warnUnmeasured(); + flushEchoes(); +} + +RuntimeEvaluator::~RuntimeEvaluator() { + m_stopGc = true; + m_gcCv.notify_all(); + if (m_gcThread.joinable()) + m_gcThread.join(); +} + +Value RuntimeEvaluator::lookup(const std::string& name) { + for (auto it = m_env.rbegin(); it != m_env.rend(); ++it) { + auto fit = it->find(name); + if (fit != it->end()) + return fit->second.value; } - - void RuntimeEvaluator::assign(const std::string& name, const Value& v) { - for (auto it = m_env.rbegin(); it != m_env.rend(); ++it) { - auto fit = it->find(name); - if (fit != it->end()) { - Value newVal = v; - if (fit->second.value.type == Value::Type::Object && - newVal.type == Value::Type::Object && newVal.objectValue && - !fit->second.value.className.empty()) { - newVal.className = fit->second.value.className; - } - fit->second.value = newVal; - fit->second.initialized = true; - return; - } + std::shared_ptr thisObj = currentThisObject(); + if (m_currentClassCtx) { + if (!m_inStaticContext && thisObj) { + RuntimeField* field = findInstanceField(m_currentClassCtx, name); + if (field && field->offset < thisObj->fields.size()) + return thisObj->fields[field->offset]; + } + auto [field, owner] = findStaticFieldWithOwner(m_currentClassCtx, name); + if (field && owner && field->offset < owner->staticStorage.size()) + return owner->staticStorage[field->offset]; + } + auto clsIt = m_classTable.find(name); + if (clsIt != m_classTable.end()) { + Value v; + v.type = Value::Type::ClassRef; + v.classRef = clsIt->second.get(); + v.className = name; + return v; + } + auto tmplIt = m_genericTemplates.find(name); + if (tmplIt != m_genericTemplates.end()) { + Value v; + v.type = Value::Type::ClassRef; + v.classRef = nullptr; + v.className = name; + return v; + } + return {}; +} + +void RuntimeEvaluator::assign(const std::string& name, const Value& v) { + for (auto it = m_env.rbegin(); it != m_env.rend(); ++it) { + auto fit = it->find(name); + if (fit != it->end()) { + Value newVal = v; + if (fit->second.value.type == Value::Type::Object && + newVal.type == Value::Type::Object && newVal.objectValue && + !fit->second.value.className.empty()) { + newVal.className = fit->second.value.className; + } + fit->second.value = newVal; + fit->second.initialized = true; + return; } - std::shared_ptr thisObj = currentThisObject(); - if (m_currentClassCtx) { - if (!m_inStaticContext && thisObj) { - RuntimeField* field = findInstanceField(m_currentClassCtx, name); - if (field && field->offset < thisObj->fields.size()) { - Value newVal = v; - const Value& existing = thisObj->fields[field->offset]; - if (existing.type == Value::Type::Object && - newVal.type == Value::Type::Object && newVal.objectValue && - !existing.className.empty()) { - newVal.className = existing.className; - } - thisObj->fields[field->offset] = newVal; - return; - } - } - auto [field, owner] = findStaticFieldWithOwner(m_currentClassCtx, name); - if (field && owner && field->offset < owner->staticStorage.size()) { + } + std::shared_ptr thisObj = currentThisObject(); + if (m_currentClassCtx) { + if (!m_inStaticContext && thisObj) { + RuntimeField* field = findInstanceField(m_currentClassCtx, name); + if (field && field->offset < thisObj->fields.size()) { Value newVal = v; - const Value& existing = owner->staticStorage[field->offset]; + const Value& existing = thisObj->fields[field->offset]; if (existing.type == Value::Type::Object && newVal.type == Value::Type::Object && newVal.objectValue && !existing.className.empty()) { newVal.className = existing.className; } - owner->staticStorage[field->offset] = newVal; + thisObj->fields[field->offset] = newVal; return; } } - m_env.back()[name] = {v, false, true}; + auto [field, owner] = findStaticFieldWithOwner(m_currentClassCtx, name); + if (field && owner && field->offset < owner->staticStorage.size()) { + Value newVal = v; + const Value& existing = owner->staticStorage[field->offset]; + if (existing.type == Value::Type::Object && newVal.type == Value::Type::Object && + newVal.objectValue && !existing.className.empty()) { + newVal.className = existing.className; + } + owner->staticStorage[field->offset] = newVal; + return; + } } - - std::shared_ptr RuntimeEvaluator::currentThisObject() const { - for (auto it = m_env.rbegin(); it != m_env.rend(); ++it) { - auto found = it->find("this"); - if (found != it->end() && found->second.value.objectValue) - return found->second.value.objectValue; + m_env.back()[name] = {v, false, true}; +} + +std::shared_ptr RuntimeEvaluator::currentThisObject() const { + for (auto it = m_env.rbegin(); it != m_env.rend(); ++it) { + auto found = it->find("this"); + if (found != it->end() && found->second.value.objectValue) + return found->second.value.objectValue; + } + return {}; +} + +RuntimeClass* RuntimeEvaluator::findClass(const std::string& name) const { + auto it = m_classTable.find(name); + if (it != m_classTable.end()) + return it->second.get(); + return nullptr; +} + +RuntimeField* RuntimeEvaluator::findInstanceField(RuntimeClass* cls, const std::string& name) { + RuntimeClass* cur = cls; + while (cur) { + auto fit = cur->instanceFieldIndex.find(name); + if (fit != cur->instanceFieldIndex.end()) + return &cur->instanceFields[fit->second]; + cur = cur->base; + } + return nullptr; +} + +RuntimeField* RuntimeEvaluator::findStaticField(RuntimeClass* cls, const std::string& name) { + RuntimeClass* cur = cls; + while (cur) { + auto fit = cur->staticFieldIndex.find(name); + if (fit != cur->staticFieldIndex.end()) + return &cur->staticFields[fit->second]; + cur = cur->base; + } + return nullptr; +} + +static std::string runtimeSignatureLabel(const std::string& name, + const std::vector& params) { + std::ostringstream oss; + oss << name << "("; + for (size_t i = 0; i < params.size(); ++i) { + if (i) + oss << ","; + if (!params[i].className.empty()) + oss << params[i].className; + else { + switch (params[i].kind) { + case Value::Type::Int: + oss << "int"; + break; + case Value::Type::Float: + oss << "float"; + break; + case Value::Type::Bit: + oss << "bit"; + break; + case Value::Type::String: + oss << "string"; + break; + case Value::Type::Char: + oss << "char"; + break; + case Value::Type::Qubit: + oss << "qubit"; + break; + case Value::Type::Object: + oss << "object"; + break; + case Value::Type::ObjectArray: + oss << "object[]"; + break; + default: + oss << "unknown"; + break; + } } - return {}; } + oss << ")"; + return oss.str(); +} - RuntimeClass* RuntimeEvaluator::findClass(const std::string& name) const { - auto it = m_classTable.find(name); - if (it != m_classTable.end()) - return it->second.get(); - return nullptr; +int RuntimeEvaluator::runtimeInheritanceDistance(const std::string& derived, + const std::string& base) const { + if (derived.empty() || base.empty()) + return -1; + if (derived == base) + return 0; + int distance = 0; + RuntimeClass* cur = findClass(derived); + while (cur) { + if (cur->name == base) + return distance; + cur = cur->base; + ++distance; } - - RuntimeField* RuntimeEvaluator::findInstanceField(RuntimeClass* cls, const std::string& name) { - RuntimeClass* cur = cls; - while (cur) { - auto fit = cur->instanceFieldIndex.find(name); - if (fit != cur->instanceFieldIndex.end()) - return &cur->instanceFields[fit->second]; - cur = cur->base; + return -1; +} + +bool RuntimeEvaluator::isRuntimeSubclassOf(const std::string& derived, + const std::string& base) const { + return runtimeInheritanceDistance(derived, base) >= 0; +} + +std::optional RuntimeEvaluator::valueConversionCost(const RuntimeTypeInfo& expected, + const Value& actual) const { + switch (expected.kind) { + case Value::Type::Int: + return actual.type == Value::Type::Int ? std::optional(0) : std::nullopt; + case Value::Type::Long: + if (actual.type == Value::Type::Long) + return 0; + if (actual.type == Value::Type::Int) + return 1; + return std::nullopt; + case Value::Type::Float: + return actual.type == Value::Type::Float ? std::optional(0) : std::nullopt; + case Value::Type::Bit: + return actual.type == Value::Type::Bit ? std::optional(0) : std::nullopt; + case Value::Type::Boolean: + return actual.type == Value::Type::Boolean ? std::optional(0) : std::nullopt; + case Value::Type::String: + return actual.type == Value::Type::String ? std::optional(0) : std::nullopt; + case Value::Type::Char: + return actual.type == Value::Type::Char ? std::optional(0) : std::nullopt; + case Value::Type::Qubit: + return actual.type == Value::Type::Qubit ? std::optional(0) : std::nullopt; + case Value::Type::Object: { + if (isNullReference(actual)) + return 3; + if (actual.type != Value::Type::Object) + return std::nullopt; + if (expected.className.empty()) + return 0; + std::string actualClass = actual.className; + if (actualClass.empty() && actual.objectValue && actual.objectValue->cls) + actualClass = actual.objectValue->cls->name; + if (actualClass.empty()) + return std::nullopt; + int distance = runtimeInheritanceDistance(actualClass, expected.className); + return distance >= 0 ? std::optional(distance) : std::nullopt; } - return nullptr; + case Value::Type::ObjectArray: + if (actual.type != Value::Type::ObjectArray) + return std::nullopt; + if (expected.className.empty()) + return 0; + return actual.className == expected.className ? std::optional(0) : std::nullopt; + default: + return actual.type == expected.kind ? std::optional(0) : std::nullopt; } - - RuntimeField* RuntimeEvaluator::findStaticField(RuntimeClass* cls, const std::string& name) { - RuntimeClass* cur = cls; +} + +std::optional RuntimeEvaluator::argumentsConversionCost( + const std::vector& expected, const std::vector& actual) const { + if (expected.size() != actual.size()) + return std::nullopt; + int total = 0; + for (size_t i = 0; i < expected.size(); ++i) { + auto cost = valueConversionCost(expected[i], actual[i]); + if (!cost) + return std::nullopt; + total += *cost; + } + return total; +} + +bool RuntimeEvaluator::valueMatchesType(const RuntimeTypeInfo& expected, + const Value& actual) const { + return valueConversionCost(expected, actual).has_value(); +} + +bool RuntimeEvaluator::argumentsMatchConstructor(const std::vector& args, + const RuntimeConstructor& candidate) const { + return argumentsConversionCost(candidate.params, args).has_value(); +} + +RuntimeMethod* RuntimeEvaluator::findMethod(RuntimeClass* cls, const std::string& name, + const std::vector* args) { + RuntimeClass* cur = cls; + if (!args) { while (cur) { - auto fit = cur->staticFieldIndex.find(name); - if (fit != cur->staticFieldIndex.end()) - return &cur->staticFields[fit->second]; + auto mit = cur->methods.find(name); + if (mit != cur->methods.end()) + return mit->second.empty() ? nullptr : &mit->second.front(); cur = cur->base; } return nullptr; } - static std::string runtimeSignatureLabel(const std::string& name, - const std::vector& params) { - std::ostringstream oss; - oss << name << "("; - for (size_t i = 0; i < params.size(); ++i) { - if (i) - oss << ","; - if (!params[i].className.empty()) - oss << params[i].className; - else { - switch (params[i].kind) { - case Value::Type::Int: - oss << "int"; - break; - case Value::Type::Float: - oss << "float"; - break; - case Value::Type::Bit: - oss << "bit"; - break; - case Value::Type::String: - oss << "string"; - break; - case Value::Type::Char: - oss << "char"; - break; - case Value::Type::Qubit: - oss << "qubit"; - break; - case Value::Type::Object: - oss << "object"; - break; - case Value::Type::ObjectArray: - oss << "object[]"; - break; - default: - oss << "unknown"; - break; - } + struct Candidate { + RuntimeMethod* method = nullptr; + int cost = 0; + }; + std::unordered_set hiddenSignatures; + std::vector matches; + while (cur) { + auto mit = cur->methods.find(name); + if (mit != cur->methods.end()) { + for (auto& cand : mit->second) { + if (hiddenSignatures.count(cand.signature)) + continue; + hiddenSignatures.insert(cand.signature); + auto cost = argumentsConversionCost(cand.params, *args); + if (!cost) + continue; + matches.push_back({&cand, *cost}); } } - oss << ")"; - return oss.str(); + cur = cur->base; } + if (matches.empty()) + return nullptr; - int RuntimeEvaluator::runtimeInheritanceDistance(const std::string& derived, - const std::string& base) const { - if (derived.empty() || base.empty()) - return -1; - if (derived == base) - return 0; - int distance = 0; - RuntimeClass* cur = findClass(derived); - while (cur) { - if (cur->name == base) - return distance; - cur = cur->base; - ++distance; - } - return -1; - } - - bool RuntimeEvaluator::isRuntimeSubclassOf(const std::string& derived, - const std::string& base) const { - return runtimeInheritanceDistance(derived, base) >= 0; - } - - std::optional RuntimeEvaluator::valueConversionCost(const RuntimeTypeInfo& expected, - const Value& actual) const { - switch (expected.kind) { - case Value::Type::Int: - return actual.type == Value::Type::Int ? std::optional(0) : std::nullopt; - case Value::Type::Long: - if (actual.type == Value::Type::Long) - return 0; - if (actual.type == Value::Type::Int) - return 1; - return std::nullopt; - case Value::Type::Float: - return actual.type == Value::Type::Float ? std::optional(0) : std::nullopt; - case Value::Type::Bit: - return actual.type == Value::Type::Bit ? std::optional(0) : std::nullopt; - case Value::Type::Boolean: - return actual.type == Value::Type::Boolean ? std::optional(0) : std::nullopt; - case Value::Type::String: - return actual.type == Value::Type::String ? std::optional(0) : std::nullopt; - case Value::Type::Char: - return actual.type == Value::Type::Char ? std::optional(0) : std::nullopt; - case Value::Type::Qubit: - return actual.type == Value::Type::Qubit ? std::optional(0) : std::nullopt; - case Value::Type::Object: { - if (isNullReference(actual)) - return 3; - if (actual.type != Value::Type::Object) - return std::nullopt; - if (expected.className.empty()) - return 0; - std::string actualClass = actual.className; - if (actualClass.empty() && actual.objectValue && actual.objectValue->cls) - actualClass = actual.objectValue->cls->name; - if (actualClass.empty()) - return std::nullopt; - int distance = runtimeInheritanceDistance(actualClass, expected.className); - return distance >= 0 ? std::optional(distance) : std::nullopt; - } - case Value::Type::ObjectArray: - if (actual.type != Value::Type::ObjectArray) - return std::nullopt; - if (expected.className.empty()) - return 0; - return actual.className == expected.className ? std::optional(0) - : std::nullopt; - default: - return actual.type == expected.kind ? std::optional(0) : std::nullopt; - } - } - - std::optional RuntimeEvaluator::argumentsConversionCost( - const std::vector& expected, const std::vector& actual) const { - if (expected.size() != actual.size()) - return std::nullopt; - int total = 0; - for (size_t i = 0; i < expected.size(); ++i) { - auto cost = valueConversionCost(expected[i], actual[i]); - if (!cost) - return std::nullopt; - total += *cost; + int bestCost = std::numeric_limits::max(); + RuntimeMethod* best = nullptr; + bool ambiguous = false; + for (const auto& candidate : matches) { + if (candidate.cost < bestCost) { + bestCost = candidate.cost; + best = candidate.method; + ambiguous = false; + } else if (candidate.cost == bestCost) { + ambiguous = true; } - return total; - } - - bool RuntimeEvaluator::valueMatchesType(const RuntimeTypeInfo& expected, - const Value& actual) const { - return valueConversionCost(expected, actual).has_value(); } + return ambiguous ? nullptr : best; +} - bool RuntimeEvaluator::argumentsMatchConstructor(const std::vector& args, - const RuntimeConstructor& candidate) const { - return argumentsConversionCost(candidate.params, args).has_value(); - } - - RuntimeMethod* RuntimeEvaluator::findMethod(RuntimeClass* cls, const std::string& name, - const std::vector* args) { - RuntimeClass* cur = cls; - if (!args) { - while (cur) { - auto mit = cur->methods.find(name); - if (mit != cur->methods.end()) - return mit->second.empty() ? nullptr : &mit->second.front(); - cur = cur->base; - } - return nullptr; - } - - struct Candidate { - RuntimeMethod* method = nullptr; - int cost = 0; - }; - std::unordered_set hiddenSignatures; - std::vector matches; - while (cur) { - auto mit = cur->methods.find(name); - if (mit != cur->methods.end()) { - for (auto& cand : mit->second) { - if (hiddenSignatures.count(cand.signature)) - continue; - hiddenSignatures.insert(cand.signature); - auto cost = argumentsConversionCost(cand.params, *args); - if (!cost) - continue; - matches.push_back({&cand, *cost}); - } - } - cur = cur->base; - } - if (matches.empty()) - return nullptr; +void RuntimeEvaluator::buildClassTable(Program& program) { + m_classTable.clear(); + m_genericTemplates.clear(); - int bestCost = std::numeric_limits::max(); - RuntimeMethod* best = nullptr; - bool ambiguous = false; - for (const auto& candidate : matches) { - if (candidate.cost < bestCost) { - bestCost = candidate.cost; - best = candidate.method; - ambiguous = false; - } else if (candidate.cost == bestCost) { - ambiguous = true; - } + bool hasExplicitObjectClass = false; + for (const auto& clsNode : program.classes) { + if (clsNode && clsNode->name == "Object") { + hasExplicitObjectClass = true; + break; } - return ambiguous ? nullptr : best; } - - void RuntimeEvaluator::buildClassTable(Program& program) { - m_classTable.clear(); - m_genericTemplates.clear(); - - bool hasExplicitObjectClass = false; - for (const auto& clsNode : program.classes) { - if (clsNode && clsNode->name == "Object") { - hasExplicitObjectClass = true; - break; - } - } - if (!hasExplicitObjectClass) { - auto root = std::make_shared(); - root->name = "Object"; - root->isStatic = false; - root->isAbstract = false; - RuntimeConstructor ctor; - ctor.decl = nullptr; - ctor.isDefault = true; - root->constructors.push_back(std::move(ctor)); - m_classTable[root->name] = std::move(root); - } - - for (auto& clsNode : program.classes) { - if (!clsNode) - continue; - if (!clsNode->typeParameters.empty()) { - m_genericTemplates[clsNode->name] = clsNode.get(); - continue; - } - if (m_classTable.count(clsNode->name)) - continue; - auto rc = std::make_shared(); - rc->name = clsNode->name; - rc->isStatic = clsNode->isStatic; - rc->isAbstract = clsNode->isAbstract; - m_classTable[rc->name] = rc; - } - // populate members - for (auto& clsNode : program.classes) { - if (!clsNode || !clsNode->typeParameters.empty()) - continue; // generic templates handled lazily - RuntimeClass* rc = findClass(clsNode->name); - if (!rc) - continue; - // Wire base (non-generic class) - if (clsNode->baseType) { - if (auto named = dynamic_cast(clsNode->baseType.get())) { - if (named->typeArguments.empty()) { - rc->base = findClass(named->nameParts.back()); - } else { - rc->base = instantiateGeneric(named, {}); - } - } - } else if (!clsNode->baseName.empty()) { - rc->base = findClass(clsNode->baseName.back()); - } else if (!rc->isStatic && rc->name != "Object") { - rc->base = findClass("Object"); - } - if (rc->base) { - rc->instanceFields = rc->base->instanceFields; - rc->instanceFieldIndex = rc->base->instanceFieldIndex; - rc->vtable = rc->base->vtable; - } - for (auto& member : clsNode->members) { - if (auto field = dynamic_cast(member.get())) { - RuntimeField f; - f.name = field->name; - f.type = typeInfoFromAst(field->fieldType.get()); - f.isStatic = field->isStatic; - f.isFinal = field->isFinal; - f.isTracked = field->isTracked; - f.initializer = field->initializer.get(); - f.hasInitializer = field->initializer != nullptr; - if (auto arr = dynamic_cast(field->fieldType.get())) - f.arraySize = arr->size; - f.line = field->line; - f.column = field->column; - if (f.isTracked || f.type.kind == Value::Type::Qubit || - f.type.kind == Value::Type::QubitArray) - rc->hasTrackedFields = true; - if (f.isStatic) { - f.offset = rc->staticFields.size(); - rc->staticFieldIndex[f.name] = f.offset; - rc->staticFields.push_back(f); - } else { - f.offset = rc->instanceFields.size(); - rc->instanceFieldIndex[f.name] = f.offset; - rc->instanceFields.push_back(f); - } - } else if (auto method = dynamic_cast(member.get())) { - RuntimeMethod m; - m.decl = method; - m.isStatic = method->isStatic; - m.isVirtual = method->isVirtual; - m.isOverride = method->isOverride; - m.owner = rc; - for (auto& p : method->params) - m.params.push_back(typeInfoFromAst(p->type.get())); - m.signature = runtimeSignatureLabel(method->name, m.params); - auto& bucket = rc->methods[method->name]; - bucket.push_back(m); - RuntimeMethod* stored = &bucket.back(); - if (stored->isVirtual || stored->isOverride) { - RuntimeMethod* baseMethod = nullptr; - if (rc->base) { - auto it = rc->base->methods.find(method->name); - if (it != rc->base->methods.end()) { - for (auto& cand : it->second) { - if (cand.signature == stored->signature) { - baseMethod = &cand; - break; - } - } - } - } - rc->vtable[stored->signature] = stored; - if (baseMethod) { - rc->vtable[stored->signature] = stored; - } - } - } else if (auto ctor = dynamic_cast(member.get())) { - RuntimeConstructor c; - c.decl = ctor; - for (auto& p : ctor->params) c.params.push_back(typeInfoFromAst(p->type.get())); - c.isDefault = ctor->isDefault; - rc->constructors.push_back(c); - } else if (auto dtor = dynamic_cast(member.get())) { - rc->hasDestructor = true; - rc->destructorDecl = dtor; - } - } - if (rc->staticStorage.size() < rc->staticFields.size()) - rc->staticStorage.resize(rc->staticFields.size()); - } + if (!hasExplicitObjectClass) { + auto root = std::make_shared(); + root->name = "Object"; + root->isStatic = false; + root->isAbstract = false; + RuntimeConstructor ctor; + ctor.decl = nullptr; + ctor.isDefault = true; + root->constructors.push_back(std::move(ctor)); + m_classTable[root->name] = std::move(root); } - RuntimeClass* RuntimeEvaluator::instantiateGeneric( - const NamedType* typeNode, const std::unordered_map& subst) { - if (!typeNode || typeNode->nameParts.empty()) - return nullptr; - std::string base = typeNode->nameParts.back(); - auto tmplIt = m_genericTemplates.find(base); - if (tmplIt == m_genericTemplates.end()) - return nullptr; - std::vector argInfos; - for (auto& arg : typeNode->typeArguments) - argInfos.push_back(typeInfoFromAst(arg.get(), subst)); - RuntimeTypeInfo assembled; - assembled.kind = Value::Type::Object; - assembled.className = base; - assembled.typeArgs = argInfos; - std::string key = typeKey(assembled); - if (auto existing = findClass(key)) - return existing; - - compiler::ClassDeclaration* tmpl = tmplIt->second; - std::unordered_map localSubst = subst; - for (size_t i = 0; i < tmpl->typeParameters.size() && i < argInfos.size(); ++i) { - localSubst[tmpl->typeParameters[i]->name] = argInfos[i]; + for (auto& clsNode : program.classes) { + if (!clsNode) + continue; + if (!clsNode->typeParameters.empty()) { + m_genericTemplates[clsNode->name] = clsNode.get(); + continue; } - + if (m_classTable.count(clsNode->name)) + continue; auto rc = std::make_shared(); - rc->name = key; - rc->isStatic = tmpl->isStatic; - rc->isAbstract = tmpl->isAbstract; - rc->typeArgs = argInfos; - for (auto& tp : tmpl->typeParameters) rc->typeParamNames.push_back(tp->name); - if (tmpl->baseType) { - if (auto baseNamed = dynamic_cast(tmpl->baseType.get())) { - if (baseNamed->typeArguments.empty()) { - rc->base = findClass(baseNamed->nameParts.back()); + rc->name = clsNode->name; + rc->isStatic = clsNode->isStatic; + rc->isAbstract = clsNode->isAbstract; + m_classTable[rc->name] = rc; + } + // populate members + for (auto& clsNode : program.classes) { + if (!clsNode || !clsNode->typeParameters.empty()) + continue; // generic templates handled lazily + RuntimeClass* rc = findClass(clsNode->name); + if (!rc) + continue; + // Wire base (non-generic class) + if (clsNode->baseType) { + if (auto named = dynamic_cast(clsNode->baseType.get())) { + if (named->typeArguments.empty()) { + rc->base = findClass(named->nameParts.back()); } else { - rc->base = instantiateGeneric(baseNamed, localSubst); + rc->base = instantiateGeneric(named, {}); } } - } else if (!tmpl->baseName.empty()) { - rc->base = findClass(tmpl->baseName.back()); + } else if (!clsNode->baseName.empty()) { + rc->base = findClass(clsNode->baseName.back()); } else if (!rc->isStatic && rc->name != "Object") { rc->base = findClass("Object"); } @@ -1070,12 +945,11 @@ namespace bloch::runtime { rc->instanceFieldIndex = rc->base->instanceFieldIndex; rc->vtable = rc->base->vtable; } - - for (auto& member : tmpl->members) { + for (auto& member : clsNode->members) { if (auto field = dynamic_cast(member.get())) { RuntimeField f; f.name = field->name; - f.type = typeInfoFromAst(field->fieldType.get(), localSubst); + f.type = typeInfoFromAst(field->fieldType.get()); f.isStatic = field->isStatic; f.isFinal = field->isFinal; f.isTracked = field->isTracked; @@ -1103,9 +977,9 @@ namespace bloch::runtime { m.isStatic = method->isStatic; m.isVirtual = method->isVirtual; m.isOverride = method->isOverride; - m.owner = rc.get(); + m.owner = rc; for (auto& p : method->params) - m.params.push_back(typeInfoFromAst(p->type.get(), localSubst)); + m.params.push_back(typeInfoFromAst(p->type.get())); m.signature = runtimeSignatureLabel(method->name, m.params); auto& bucket = rc->methods[method->name]; bucket.push_back(m); @@ -1132,7 +1006,7 @@ namespace bloch::runtime { RuntimeConstructor c; c.decl = ctor; for (auto& p : ctor->params) - c.params.push_back(typeInfoFromAst(p->type.get(), localSubst)); + c.params.push_back(typeInfoFromAst(p->type.get())); c.isDefault = ctor->isDefault; rc->constructors.push_back(c); } else if (auto dtor = dynamic_cast(member.get())) { @@ -1142,2120 +1016,2238 @@ namespace bloch::runtime { } if (rc->staticStorage.size() < rc->staticFields.size()) rc->staticStorage.resize(rc->staticFields.size()); - m_classTable[key] = rc; - initStaticFields(rc.get()); - return rc.get(); - } - - RuntimeClass* RuntimeEvaluator::instantiateGeneric(const NamedType* typeNode) { - static const std::unordered_map emptySubst; - return instantiateGeneric(typeNode, emptySubst); } +} - RuntimeClass* RuntimeEvaluator::instantiateGeneric(const std::string& base, - const std::vector& args) { - auto tmplIt = m_genericTemplates.find(base); - if (tmplIt == m_genericTemplates.end()) - return nullptr; - auto nt = std::make_unique(std::vector{base}); - for (const auto& a : args) nt->typeArguments.push_back(runtimeTypeToAst(a)); - std::unordered_map subst; - compiler::ClassDeclaration* tmpl = tmplIt->second; - for (size_t i = 0; i < tmpl->typeParameters.size() && i < args.size(); ++i) { - subst[tmpl->typeParameters[i]->name] = args[i]; - } - return instantiateGeneric(nt.get(), subst); +RuntimeClass* RuntimeEvaluator::instantiateGeneric( + const NamedType* typeNode, const std::unordered_map& subst) { + if (!typeNode || typeNode->nameParts.empty()) + return nullptr; + std::string base = typeNode->nameParts.back(); + auto tmplIt = m_genericTemplates.find(base); + if (tmplIt == m_genericTemplates.end()) + return nullptr; + std::vector argInfos; + for (auto& arg : typeNode->typeArguments) + argInfos.push_back(typeInfoFromAst(arg.get(), subst)); + RuntimeTypeInfo assembled; + assembled.kind = Value::Type::Object; + assembled.className = base; + assembled.typeArgs = argInfos; + std::string key = typeKey(assembled); + if (auto existing = findClass(key)) + return existing; + + compiler::ClassDeclaration* tmpl = tmplIt->second; + std::unordered_map localSubst = subst; + for (size_t i = 0; i < tmpl->typeParameters.size() && i < argInfos.size(); ++i) { + localSubst[tmpl->typeParameters[i]->name] = argInfos[i]; } - void RuntimeEvaluator::initStaticFields(RuntimeClass* cls) { - if (!cls) - return; - for (size_t i = 0; i < cls->staticFields.size(); ++i) { - auto& field = cls->staticFields[i]; - auto& slot = cls->staticStorage[i]; - if (slot.type != Value::Type::Void) - continue; - bool prevStatic = m_inStaticContext; - auto* prevClass = m_currentClassCtx; - m_inStaticContext = true; - m_currentClassCtx = cls; - slot = defaultValueForField(field, cls->name); - if (field.hasInitializer && field.initializer) { - slot = eval(field.initializer); + auto rc = std::make_shared(); + rc->name = key; + rc->isStatic = tmpl->isStatic; + rc->isAbstract = tmpl->isAbstract; + rc->typeArgs = argInfos; + for (auto& tp : tmpl->typeParameters) + rc->typeParamNames.push_back(tp->name); + if (tmpl->baseType) { + if (auto baseNamed = dynamic_cast(tmpl->baseType.get())) { + if (baseNamed->typeArguments.empty()) { + rc->base = findClass(baseNamed->nameParts.back()); + } else { + rc->base = instantiateGeneric(baseNamed, localSubst); } - m_inStaticContext = prevStatic; - m_currentClassCtx = prevClass; } + } else if (!tmpl->baseName.empty()) { + rc->base = findClass(tmpl->baseName.back()); + } else if (!rc->isStatic && rc->name != "Object") { + rc->base = findClass("Object"); + } + if (rc->base) { + rc->instanceFields = rc->base->instanceFields; + rc->instanceFieldIndex = rc->base->instanceFieldIndex; + rc->vtable = rc->base->vtable; } - void RuntimeEvaluator::ensureGcThread() { - if (m_gcThread.joinable()) - return; - m_stopGc = false; - m_gcRequested = false; - m_gcThreadStarted = true; - m_gcThread = std::thread([this]() { - std::unique_lock lock(m_gcMutex); - while (!m_stopGc.load()) { - m_gcCv.wait_for(lock, std::chrono::milliseconds(50), - [this]() { return m_stopGc.load(); }); - if (m_stopGc.load()) - break; - requestGc(); + for (auto& member : tmpl->members) { + if (auto field = dynamic_cast(member.get())) { + RuntimeField f; + f.name = field->name; + f.type = typeInfoFromAst(field->fieldType.get(), localSubst); + f.isStatic = field->isStatic; + f.isFinal = field->isFinal; + f.isTracked = field->isTracked; + f.initializer = field->initializer.get(); + f.hasInitializer = field->initializer != nullptr; + if (auto arr = dynamic_cast(field->fieldType.get())) + f.arraySize = arr->size; + f.line = field->line; + f.column = field->column; + if (f.isTracked || f.type.kind == Value::Type::Qubit || + f.type.kind == Value::Type::QubitArray) + rc->hasTrackedFields = true; + if (f.isStatic) { + f.offset = rc->staticFields.size(); + rc->staticFieldIndex[f.name] = f.offset; + rc->staticFields.push_back(f); + } else { + f.offset = rc->instanceFields.size(); + rc->instanceFieldIndex[f.name] = f.offset; + rc->instanceFields.push_back(f); + } + } else if (auto method = dynamic_cast(member.get())) { + RuntimeMethod m; + m.decl = method; + m.isStatic = method->isStatic; + m.isVirtual = method->isVirtual; + m.isOverride = method->isOverride; + m.owner = rc.get(); + for (auto& p : method->params) + m.params.push_back(typeInfoFromAst(p->type.get(), localSubst)); + m.signature = runtimeSignatureLabel(method->name, m.params); + auto& bucket = rc->methods[method->name]; + bucket.push_back(m); + RuntimeMethod* stored = &bucket.back(); + if (stored->isVirtual || stored->isOverride) { + RuntimeMethod* baseMethod = nullptr; + if (rc->base) { + auto it = rc->base->methods.find(method->name); + if (it != rc->base->methods.end()) { + for (auto& cand : it->second) { + if (cand.signature == stored->signature) { + baseMethod = &cand; + break; + } + } + } + } + rc->vtable[stored->signature] = stored; + if (baseMethod) { + rc->vtable[stored->signature] = stored; + } } - }); + } else if (auto ctor = dynamic_cast(member.get())) { + RuntimeConstructor c; + c.decl = ctor; + for (auto& p : ctor->params) + c.params.push_back(typeInfoFromAst(p->type.get(), localSubst)); + c.isDefault = ctor->isDefault; + rc->constructors.push_back(c); + } else if (auto dtor = dynamic_cast(member.get())) { + rc->hasDestructor = true; + rc->destructorDecl = dtor; + } } - - void RuntimeEvaluator::requestGc() { m_gcRequested = true; } - - void RuntimeEvaluator::markObject(const std::shared_ptr& obj) { - if (!obj || obj->marked) - return; - obj->marked = true; - for (const auto& field : obj->fields) markValue(field); + if (rc->staticStorage.size() < rc->staticFields.size()) + rc->staticStorage.resize(rc->staticFields.size()); + m_classTable[key] = rc; + initStaticFields(rc.get()); + return rc.get(); +} + +RuntimeClass* RuntimeEvaluator::instantiateGeneric(const NamedType* typeNode) { + static const std::unordered_map emptySubst; + return instantiateGeneric(typeNode, emptySubst); +} + +RuntimeClass* RuntimeEvaluator::instantiateGeneric(const std::string& base, + const std::vector& args) { + auto tmplIt = m_genericTemplates.find(base); + if (tmplIt == m_genericTemplates.end()) + return nullptr; + auto nt = std::make_unique(std::vector{base}); + for (const auto& a : args) + nt->typeArguments.push_back(runtimeTypeToAst(a)); + std::unordered_map subst; + compiler::ClassDeclaration* tmpl = tmplIt->second; + for (size_t i = 0; i < tmpl->typeParameters.size() && i < args.size(); ++i) { + subst[tmpl->typeParameters[i]->name] = args[i]; } - - void RuntimeEvaluator::markValue(const Value& v) { - if (v.type == Value::Type::Object && v.objectValue) { - markObject(v.objectValue); - } else if (v.type == Value::Type::ObjectArray) { - for (const auto& o : v.objectArray) markObject(o); + return instantiateGeneric(nt.get(), subst); +} + +void RuntimeEvaluator::initStaticFields(RuntimeClass* cls) { + if (!cls) + return; + for (size_t i = 0; i < cls->staticFields.size(); ++i) { + auto& field = cls->staticFields[i]; + auto& slot = cls->staticStorage[i]; + if (slot.type != Value::Type::Void) + continue; + bool prevStatic = m_inStaticContext; + auto* prevClass = m_currentClassCtx; + m_inStaticContext = true; + m_currentClassCtx = cls; + slot = defaultValueForField(field, cls->name); + if (field.hasInitializer && field.initializer) { + slot = eval(field.initializer); } + m_inStaticContext = prevStatic; + m_currentClassCtx = prevClass; } - - void RuntimeEvaluator::runCycleCollector() { - if (!m_gcRequested.load()) - return; - m_gcRequested = false; - std::vector> objects; - { - std::lock_guard lock(m_heapMutex); - std::vector> alive; - for (auto& w : m_heap) { - if (auto obj = w.lock()) { - obj->marked = false; - objects.push_back(obj); - alive.push_back(obj); - } +} + +void RuntimeEvaluator::ensureGcThread() { + if (m_gcThread.joinable()) + return; + m_stopGc = false; + m_gcRequested = false; + m_gcThreadStarted = true; + m_gcThread = std::thread([this]() { + std::unique_lock lock(m_gcMutex); + while (!m_stopGc.load()) { + m_gcCv.wait_for(lock, std::chrono::milliseconds(50), + [this]() { return m_stopGc.load(); }); + if (m_stopGc.load()) + break; + requestGc(); + } + }); +} + +void RuntimeEvaluator::requestGc() { m_gcRequested = true; } + +void RuntimeEvaluator::markObject(const std::shared_ptr& obj) { + if (!obj || obj->marked) + return; + obj->marked = true; + for (const auto& field : obj->fields) + markValue(field); +} + +void RuntimeEvaluator::markValue(const Value& v) { + if (v.type == Value::Type::Object && v.objectValue) { + markObject(v.objectValue); + } else if (v.type == Value::Type::ObjectArray) { + for (const auto& o : v.objectArray) + markObject(o); + } +} + +void RuntimeEvaluator::runCycleCollector() { + if (!m_gcRequested.load()) + return; + m_gcRequested = false; + std::vector> objects; + { + std::lock_guard lock(m_heapMutex); + std::vector> alive; + for (auto& w : m_heap) { + if (auto obj = w.lock()) { + obj->marked = false; + objects.push_back(obj); + alive.push_back(obj); } - m_heap.swap(alive); - } - if (objects.empty()) - return; - // Mark roots: environment variables and static storage - for (const auto& scope : m_env) { - for (const auto& kv : scope) markValue(kv.second.value); } - for (const auto& kv : m_classTable) { - const auto& cls = kv.second; - for (const auto& v : cls->staticStorage) markValue(v); + m_heap.swap(alive); + } + if (objects.empty()) + return; + // Mark roots: environment variables and static storage + for (const auto& scope : m_env) { + for (const auto& kv : scope) + markValue(kv.second.value); + } + for (const auto& kv : m_classTable) { + const auto& cls = kv.second; + for (const auto& v : cls->staticStorage) + markValue(v); + } + markValue(m_returnValue); + // Sweep unmarked non-tracked objects + std::vector> unreachable; + for (auto& obj : objects) { + if (!obj->marked && obj->cls && !obj->cls->hasTrackedFields) { + obj->skipDestructor = true; + unreachable.push_back(obj); } - markValue(m_returnValue); - // Sweep unmarked non-tracked objects - std::vector> unreachable; - for (auto& obj : objects) { - if (!obj->marked && obj->cls && !obj->cls->hasTrackedFields) { - obj->skipDestructor = true; - unreachable.push_back(obj); + } + for (auto& obj : unreachable) { + for (auto& f : obj->fields) + f = {}; + } + // unreachable will drop here and be reclaimed without running destructors + m_allocSinceGc = 0; +} + +void RuntimeEvaluator::recordTrackedValue(const std::string& name, const Value& v) { + if (v.type == Value::Type::Qubit) { + int q = v.qubit; + std::string outcome = "?"; + if (q >= 0 && q < static_cast(m_lastMeasurement.size()) && + m_lastMeasurement[q] != -1) { + outcome = m_lastMeasurement[q] ? "1" : "0"; + } + m_trackedCounts[name][outcome]++; + } else if (v.type == Value::Type::QubitArray) { + bool allMeasured = true; + std::string bits; + for (int q : v.qubitArray) { + if (!(q >= 0 && q < static_cast(m_lastMeasurement.size()) && + m_lastMeasurement[q] != -1)) { + allMeasured = false; + break; } } - for (auto& obj : unreachable) { - for (auto& f : obj->fields) f = {}; + std::string outcome = "?"; + if (allMeasured) { + for (int q : v.qubitArray) + bits.push_back(m_lastMeasurement[q] ? '1' : '0'); + outcome = bits; } - // unreachable will drop here and be reclaimed without running destructors - m_allocSinceGc = 0; + m_trackedCounts[name][outcome]++; } +} - void RuntimeEvaluator::recordTrackedValue(const std::string& name, const Value& v) { - if (v.type == Value::Type::Qubit) { - int q = v.qubit; - std::string outcome = "?"; - if (q >= 0 && q < static_cast(m_lastMeasurement.size()) && - m_lastMeasurement[q] != -1) { - outcome = m_lastMeasurement[q] ? "1" : "0"; - } - m_trackedCounts[name][outcome]++; - } else if (v.type == Value::Type::QubitArray) { - bool allMeasured = true; - std::string bits; - for (int q : v.qubitArray) { - if (!(q >= 0 && q < static_cast(m_lastMeasurement.size()) && - m_lastMeasurement[q] != -1)) { - allMeasured = false; +void RuntimeEvaluator::destroyObject(Object* obj, bool runUserDestructor) { + if (!obj || obj->destroyed) + return; + obj->destroyed = true; + if (runUserDestructor && obj->cls) { + bool savedReturn = m_hasReturn; + for (RuntimeClass* cur = obj->cls; cur; cur = cur->base) { + if (!cur->destructorDecl || !cur->destructorDecl->body) + continue; + auto prevClass = m_currentClassCtx; + auto prevStatic = m_inStaticContext; + auto prevCtor = m_inConstructor; + auto prevDtor = m_inDestructor; + m_currentClassCtx = cur; + m_inStaticContext = false; + m_inConstructor = false; + m_inDestructor = true; + beginScope(); + Value thisVal; + thisVal.type = Value::Type::Object; + thisVal.objectValue = std::shared_ptr(obj, [](Object*) {}); + thisVal.className = cur->name; + m_env.back()["this"] = {thisVal, false, true}; + for (auto& stmt : cur->destructorDecl->body->statements) { + exec(stmt.get()); + if (m_hasReturn) break; - } } - std::string outcome = "?"; - if (allMeasured) { - for (int q : v.qubitArray) bits.push_back(m_lastMeasurement[q] ? '1' : '0'); - outcome = bits; - } - m_trackedCounts[name][outcome]++; + endScope(); + m_inDestructor = prevDtor; + m_inConstructor = prevCtor; + m_inStaticContext = prevStatic; + m_currentClassCtx = prevClass; } + m_hasReturn = savedReturn; } - - void RuntimeEvaluator::destroyObject(Object* obj, bool runUserDestructor) { - if (!obj || obj->destroyed) - return; - obj->destroyed = true; - if (runUserDestructor && obj->cls) { - bool savedReturn = m_hasReturn; - for (RuntimeClass* cur = obj->cls; cur; cur = cur->base) { - if (!cur->destructorDecl || !cur->destructorDecl->body) - continue; - auto prevClass = m_currentClassCtx; - auto prevStatic = m_inStaticContext; - auto prevCtor = m_inConstructor; - auto prevDtor = m_inDestructor; - m_currentClassCtx = cur; - m_inStaticContext = false; - m_inConstructor = false; - m_inDestructor = true; - beginScope(); - Value thisVal; - thisVal.type = Value::Type::Object; - thisVal.objectValue = std::shared_ptr(obj, [](Object*) {}); - thisVal.className = cur->name; - m_env.back()["this"] = {thisVal, false, true}; - for (auto& stmt : cur->destructorDecl->body->statements) { - exec(stmt.get()); - if (m_hasReturn) - break; - } - endScope(); - m_inDestructor = prevDtor; - m_inConstructor = prevCtor; - m_inStaticContext = prevStatic; - m_currentClassCtx = prevClass; - } - m_hasReturn = savedReturn; - } - // Reset tracked qubits - if (obj->cls) { - for (size_t i = 0; i < obj->fields.size(); ++i) { - if (i >= obj->cls->instanceFields.size()) - continue; - const auto& fieldMeta = obj->cls->instanceFields[i]; - if (fieldMeta.isTracked && (obj->fields[i].type == Value::Type::Qubit || - obj->fields[i].type == Value::Type::QubitArray)) { - recordTrackedValue(obj->cls->name + "." + fieldMeta.name, obj->fields[i]); - } - if (obj->fields[i].type == Value::Type::Qubit) { - int q = obj->fields[i].qubit; + // Reset tracked qubits + if (obj->cls) { + for (size_t i = 0; i < obj->fields.size(); ++i) { + if (i >= obj->cls->instanceFields.size()) + continue; + const auto& fieldMeta = obj->cls->instanceFields[i]; + if (fieldMeta.isTracked && (obj->fields[i].type == Value::Type::Qubit || + obj->fields[i].type == Value::Type::QubitArray)) { + recordTrackedValue(obj->cls->name + "." + fieldMeta.name, obj->fields[i]); + } + if (obj->fields[i].type == Value::Type::Qubit) { + int q = obj->fields[i].qubit; + ensureQubitExists(q, fieldMeta.line, fieldMeta.column); + m_sim.reset(q); + releaseQubit(q); + } else if (obj->fields[i].type == Value::Type::QubitArray) { + for (int q : obj->fields[i].qubitArray) { ensureQubitExists(q, fieldMeta.line, fieldMeta.column); m_sim.reset(q); releaseQubit(q); - } else if (obj->fields[i].type == Value::Type::QubitArray) { - for (int q : obj->fields[i].qubitArray) { - ensureQubitExists(q, fieldMeta.line, fieldMeta.column); - m_sim.reset(q); - releaseQubit(q); - } } } } - obj->fields.clear(); } - - void RuntimeEvaluator::deferRuntimeError(std::exception_ptr error) noexcept { - try { - std::lock_guard lock(m_deferredRuntimeErrorMutex); - // Preserve the first failure: it is the one that caused teardown to begin. - if (!m_deferredRuntimeError) - m_deferredRuntimeError = std::move(error); - } catch (...) { - // A deleter cannot propagate any exception. Failure to retain a diagnostic is - // preferable to terminating the host process. - } + obj->fields.clear(); +} + +void RuntimeEvaluator::deferRuntimeError(std::exception_ptr error) noexcept { + try { + std::lock_guard lock(m_deferredRuntimeErrorMutex); + // Preserve the first failure: it is the one that caused teardown to begin. + if (!m_deferredRuntimeError) + m_deferredRuntimeError = std::move(error); + } catch (...) { + // A deleter cannot propagate any exception. Failure to retain a diagnostic is + // preferable to terminating the host process. } +} - void RuntimeEvaluator::throwDeferredRuntimeError() { - std::exception_ptr error; - { - std::lock_guard lock(m_deferredRuntimeErrorMutex); - error = std::move(m_deferredRuntimeError); +void RuntimeEvaluator::throwDeferredRuntimeError() { + std::exception_ptr error; + { + std::lock_guard lock(m_deferredRuntimeErrorMutex); + error = std::move(m_deferredRuntimeError); + } + if (error) + std::rethrow_exception(error); +} + +void RuntimeEvaluator::runFieldInitialisers(RuntimeClass* cls, const std::shared_ptr& obj) { + if (!cls) + return; + size_t startIdx = cls->base ? cls->base->instanceFields.size() : 0; + if (startIdx > cls->instanceFields.size()) + startIdx = cls->instanceFields.size(); + for (size_t i = startIdx; i < cls->instanceFields.size(); ++i) { + auto& field = cls->instanceFields[i]; + if (field.isStatic) + continue; + auto& slot = obj->fields[field.offset]; + if (slot.type == Value::Type::Void) + slot = defaultValueForField(field, cls->name); + if (field.hasInitializer && field.initializer) { + auto prevClass = m_currentClassCtx; + bool prevStatic = m_inStaticContext; + m_currentClassCtx = cls; + m_inStaticContext = false; + beginScope(); + Value thisVal; + thisVal.type = Value::Type::Object; + thisVal.objectValue = obj; + thisVal.className = cls->name; + m_env.back()["this"] = {thisVal, false, true}; + Value init = eval(field.initializer); + slot = init; + endScope(); + m_currentClassCtx = prevClass; + m_inStaticContext = prevStatic; } - if (error) - std::rethrow_exception(error); } +} - void RuntimeEvaluator::runFieldInitialisers(RuntimeClass* cls, - const std::shared_ptr& obj) { - if (!cls) - return; - size_t startIdx = cls->base ? cls->base->instanceFields.size() : 0; - if (startIdx > cls->instanceFields.size()) - startIdx = cls->instanceFields.size(); - for (size_t i = startIdx; i < cls->instanceFields.size(); ++i) { - auto& field = cls->instanceFields[i]; - if (field.isStatic) - continue; - auto& slot = obj->fields[field.offset]; - if (slot.type == Value::Type::Void) - slot = defaultValueForField(field, cls->name); - if (field.hasInitializer && field.initializer) { - auto prevClass = m_currentClassCtx; - bool prevStatic = m_inStaticContext; - m_currentClassCtx = cls; - m_inStaticContext = false; - beginScope(); - Value thisVal; - thisVal.type = Value::Type::Object; - thisVal.objectValue = obj; - thisVal.className = cls->name; - m_env.back()["this"] = {thisVal, false, true}; - Value init = eval(field.initializer); - slot = init; - endScope(); - m_currentClassCtx = prevClass; - m_inStaticContext = prevStatic; - } - } - } - - void RuntimeEvaluator::runConstructorChain(RuntimeClass* cls, - const std::shared_ptr& obj, - ConstructorDeclaration* ctor, - const std::vector& args) { - if (!cls) - return; +void RuntimeEvaluator::runConstructorChain(RuntimeClass* cls, const std::shared_ptr& obj, + ConstructorDeclaration* ctor, + const std::vector& args) { + if (!cls) + return; - if (kTraceConstructors) { - std::cerr << "[ctor] " << cls->name << " args=" << args.size() << std::endl; - } + if (kTraceConstructors) { + std::cerr << "[ctor] " << cls->name << " args=" << args.size() << std::endl; + } - bool savedReturn = m_hasReturn; - m_hasReturn = false; + bool savedReturn = m_hasReturn; + m_hasReturn = false; + + // Prepare context for this constructor (needed to evaluate explicit super(...) args). + auto prevClass = m_currentClassCtx; + bool prevStatic = m_inStaticContext; + bool prevCtor = m_inConstructor; + bool prevDtor = m_inDestructor; + m_currentClassCtx = cls; + m_inStaticContext = false; + m_inConstructor = true; + m_inDestructor = false; + beginScope(); + Value thisVal; + thisVal.type = Value::Type::Object; + thisVal.objectValue = obj; + thisVal.className = cls->name; + m_env.back()["this"] = {thisVal, false, true}; + for (size_t i = 0; ctor && i < ctor->params.size() && i < args.size(); ++i) { + m_env.back()[ctor->params[i]->name] = {args[i], false, true}; + } - // Prepare context for this constructor (needed to evaluate explicit super(...) args). - auto prevClass = m_currentClassCtx; - bool prevStatic = m_inStaticContext; - bool prevCtor = m_inConstructor; - bool prevDtor = m_inDestructor; - m_currentClassCtx = cls; - m_inStaticContext = false; - m_inConstructor = true; - m_inDestructor = false; - beginScope(); - Value thisVal; - thisVal.type = Value::Type::Object; - thisVal.objectValue = obj; - thisVal.className = cls->name; - m_env.back()["this"] = {thisVal, false, true}; - for (size_t i = 0; ctor && i < ctor->params.size() && i < args.size(); ++i) { - m_env.back()[ctor->params[i]->name] = {args[i], false, true}; - } - - // Detect an explicit super(...) call as the first statement. - std::vector superArgs; - ConstructorDeclaration* superCtorDecl = nullptr; - bool hasExplicitSuper = false; - if (ctor && ctor->body && !ctor->body->statements.empty()) { - if (auto exprStmt = - dynamic_cast(ctor->body->statements[0].get())) { - if (auto call = dynamic_cast(exprStmt->expression.get())) { - if (dynamic_cast(call->callee.get())) { - hasExplicitSuper = true; - for (auto& a : call->arguments) superArgs.push_back(eval(a.get())); - } + // Detect an explicit super(...) call as the first statement. + std::vector superArgs; + ConstructorDeclaration* superCtorDecl = nullptr; + bool hasExplicitSuper = false; + if (ctor && ctor->body && !ctor->body->statements.empty()) { + if (auto exprStmt = dynamic_cast(ctor->body->statements[0].get())) { + if (auto call = dynamic_cast(exprStmt->expression.get())) { + if (dynamic_cast(call->callee.get())) { + hasExplicitSuper = true; + for (auto& a : call->arguments) + superArgs.push_back(eval(a.get())); } } } + } - // Dispatch to base constructor (explicit or default). - if (cls->base) { - if (hasExplicitSuper) { - bool matchedSuperCtor = false; - bool ambiguousSuperCtor = false; - int bestCost = std::numeric_limits::max(); - for (auto& c : cls->base->constructors) { - auto cost = argumentsConversionCost(c.params, superArgs); - if (!cost) - continue; - if (*cost < bestCost) { - bestCost = *cost; - superCtorDecl = c.decl; - matchedSuperCtor = true; - ambiguousSuperCtor = false; - } else if (*cost == bestCost) { - ambiguousSuperCtor = true; - } - } - if (!matchedSuperCtor) { - throw BlochError(ErrorCategory::Runtime, ctor ? ctor->line : 0, - ctor ? ctor->column : 0, - "no matching base constructor for 'super(...)'"); - } - if (ambiguousSuperCtor) { - throw BlochError(ErrorCategory::Runtime, ctor ? ctor->line : 0, - ctor ? ctor->column : 0, - "ambiguous base constructor for 'super(...)'"); - } - } else { - // Implicit default base constructor - int zeroArgMatches = 0; - for (auto& c : cls->base->constructors) { - if (c.params.empty()) { - superCtorDecl = c.decl; - zeroArgMatches += 1; - } - } - if (zeroArgMatches == 0) { - throw BlochError(ErrorCategory::Runtime, ctor ? ctor->line : 0, - ctor ? ctor->column : 0, - "no matching base constructor for implicit super()"); - } - if (zeroArgMatches > 1) { - throw BlochError(ErrorCategory::Runtime, ctor ? ctor->line : 0, - ctor ? ctor->column : 0, - "ambiguous base constructor for implicit super()"); + // Dispatch to base constructor (explicit or default). + if (cls->base) { + if (hasExplicitSuper) { + bool matchedSuperCtor = false; + bool ambiguousSuperCtor = false; + int bestCost = std::numeric_limits::max(); + for (auto& c : cls->base->constructors) { + auto cost = argumentsConversionCost(c.params, superArgs); + if (!cost) + continue; + if (*cost < bestCost) { + bestCost = *cost; + superCtorDecl = c.decl; + matchedSuperCtor = true; + ambiguousSuperCtor = false; + } else if (*cost == bestCost) { + ambiguousSuperCtor = true; } } - if (kTraceConstructors) { - std::cerr << "[ctor] " << cls->name << " -> base " << cls->base->name - << " args=" << superArgs.size() << std::endl; + if (!matchedSuperCtor) { + throw BlochError(ErrorCategory::Runtime, ctor ? ctor->line : 0, + ctor ? ctor->column : 0, + "no matching base constructor for 'super(...)'"); } - runConstructorChain(cls->base, obj, superCtorDecl, superArgs); - } - - // Initialise fields before running the body. - if (kTraceConstructors) { - std::cerr << "[ctor] " << cls->name << " init fields" << std::endl; - } - runFieldInitialisers(cls, obj); - - if (ctor && ctor->isDefault) { - // Default constructor: bind parameters to matching fields. - for (size_t i = 0; i < ctor->params.size() && i < args.size(); ++i) { - const auto& param = ctor->params[i]; - auto fieldMeta = findInstanceField(cls, param->name); - if (fieldMeta && fieldMeta->offset < obj->fields.size()) { - obj->fields[fieldMeta->offset] = args[i]; + if (ambiguousSuperCtor) { + throw BlochError(ErrorCategory::Runtime, ctor ? ctor->line : 0, + ctor ? ctor->column : 0, + "ambiguous base constructor for 'super(...)'"); + } + } else { + // Implicit default base constructor + int zeroArgMatches = 0; + for (auto& c : cls->base->constructors) { + if (c.params.empty()) { + superCtorDecl = c.decl; + zeroArgMatches += 1; } } - } - - if (ctor && ctor->body) { - size_t startIdx = hasExplicitSuper ? 1 : 0; // already handled - if (kTraceConstructors) { - std::cerr << "[ctor] " << cls->name << " execute body (skip=" << startIdx << ")" - << std::endl; + if (zeroArgMatches == 0) { + throw BlochError(ErrorCategory::Runtime, ctor ? ctor->line : 0, + ctor ? ctor->column : 0, + "no matching base constructor for implicit super()"); } - for (size_t i = startIdx; i < ctor->body->statements.size(); ++i) { - exec(ctor->body->statements[i].get()); - if (m_hasReturn) - break; + if (zeroArgMatches > 1) { + throw BlochError(ErrorCategory::Runtime, ctor ? ctor->line : 0, + ctor ? ctor->column : 0, + "ambiguous base constructor for implicit super()"); } } if (kTraceConstructors) { - std::cerr << "[ctor] " << cls->name << " done" << std::endl; + std::cerr << "[ctor] " << cls->name << " -> base " << cls->base->name + << " args=" << superArgs.size() << std::endl; } + runConstructorChain(cls->base, obj, superCtorDecl, superArgs); + } - endScope(); - m_currentClassCtx = prevClass; - m_inStaticContext = prevStatic; - m_inConstructor = prevCtor; - m_inDestructor = prevDtor; - m_hasReturn = savedReturn; + // Initialise fields before running the body. + if (kTraceConstructors) { + std::cerr << "[ctor] " << cls->name << " init fields" << std::endl; } + runFieldInitialisers(cls, obj); - Value RuntimeEvaluator::callMethod(RuntimeMethod* method, RuntimeClass* staticDispatchClass, - const std::shared_ptr& receiver, - const std::vector& args) { - if (!method || !method->decl) - return {}; - auto prevClass = m_currentClassCtx; - bool prevStatic = m_inStaticContext; - bool prevCtor = m_inConstructor; - bool prevDtor = m_inDestructor; - m_currentClassCtx = staticDispatchClass ? staticDispatchClass : method->owner; - m_inStaticContext = method->isStatic; - m_inConstructor = false; - m_inDestructor = false; - beginScope(); - if (!method->isStatic) { - Value thisVal; - thisVal.type = Value::Type::Object; - thisVal.objectValue = receiver; - thisVal.className = method->owner ? method->owner->name : ""; - m_env.back()["this"] = {thisVal, false, true}; - } - m_returnValue = {}; - for (size_t i = 0; i < method->decl->params.size() && i < args.size(); ++i) { - m_env.back()[method->decl->params[i]->name] = {args[i], false, true}; - } - bool prevReturn = m_hasReturn; - m_hasReturn = false; - if (method->decl->body) { - for (auto& stmt : method->decl->body->statements) { - exec(stmt.get()); - if (m_hasReturn) - break; + if (ctor && ctor->isDefault) { + // Default constructor: bind parameters to matching fields. + for (size_t i = 0; i < ctor->params.size() && i < args.size(); ++i) { + const auto& param = ctor->params[i]; + auto fieldMeta = findInstanceField(cls, param->name); + if (fieldMeta && fieldMeta->offset < obj->fields.size()) { + obj->fields[fieldMeta->offset] = args[i]; } } - Value ret = m_returnValue; - endScope(); - m_hasReturn = prevReturn; - m_currentClassCtx = prevClass; - m_inStaticContext = prevStatic; - m_inConstructor = prevCtor; - m_inDestructor = prevDtor; - return ret; } - Value RuntimeEvaluator::call(FunctionDeclaration* fn, const std::vector& args) { - // Bind parameters, run the body until a return is hit, then unwind. - beginScope(); - for (size_t i = 0; i < fn->params.size() && i < args.size(); ++i) { - m_env.back()[fn->params[i]->name] = {args[i], false, true}; - } - bool prevReturn = m_hasReturn; - m_returnValue = {}; - m_hasReturn = false; - if (fn->body) { - for (auto& stmt : fn->body->statements) { - exec(stmt.get()); - if (m_hasReturn) - break; - } + if (ctor && ctor->body) { + size_t startIdx = hasExplicitSuper ? 1 : 0; // already handled + if (kTraceConstructors) { + std::cerr << "[ctor] " << cls->name << " execute body (skip=" << startIdx << ")" + << std::endl; } - Value ret = m_returnValue; - endScope(); - m_hasReturn = prevReturn; - return ret; + for (size_t i = startIdx; i < ctor->body->statements.size(); ++i) { + exec(ctor->body->statements[i].get()); + if (m_hasReturn) + break; + } + } + if (kTraceConstructors) { + std::cerr << "[ctor] " << cls->name << " done" << std::endl; } - void RuntimeEvaluator::exec(Statement* s) { - if (m_gcRequested.load()) - runCycleCollector(); - if (!s) - return; - auto isTruthy = [](const Value& v) { - switch (v.type) { - case Value::Type::Boolean: - return v.boolValue; - case Value::Type::Bit: - return v.bitValue != 0; - case Value::Type::Int: - return v.intValue != 0; - case Value::Type::Long: - return v.longValue != 0; - case Value::Type::Float: - return v.floatValue != 0.0; - default: - return false; + endScope(); + m_currentClassCtx = prevClass; + m_inStaticContext = prevStatic; + m_inConstructor = prevCtor; + m_inDestructor = prevDtor; + m_hasReturn = savedReturn; +} + +Value RuntimeEvaluator::callMethod(RuntimeMethod* method, RuntimeClass* staticDispatchClass, + const std::shared_ptr& receiver, + const std::vector& args) { + if (!method || !method->decl) + return {}; + auto prevClass = m_currentClassCtx; + bool prevStatic = m_inStaticContext; + bool prevCtor = m_inConstructor; + bool prevDtor = m_inDestructor; + m_currentClassCtx = staticDispatchClass ? staticDispatchClass : method->owner; + m_inStaticContext = method->isStatic; + m_inConstructor = false; + m_inDestructor = false; + beginScope(); + if (!method->isStatic) { + Value thisVal; + thisVal.type = Value::Type::Object; + thisVal.objectValue = receiver; + thisVal.className = method->owner ? method->owner->name : ""; + m_env.back()["this"] = {thisVal, false, true}; + } + m_returnValue = {}; + for (size_t i = 0; i < method->decl->params.size() && i < args.size(); ++i) { + m_env.back()[method->decl->params[i]->name] = {args[i], false, true}; + } + bool prevReturn = m_hasReturn; + m_hasReturn = false; + if (method->decl->body) { + for (auto& stmt : method->decl->body->statements) { + exec(stmt.get()); + if (m_hasReturn) + break; + } + } + Value ret = m_returnValue; + endScope(); + m_hasReturn = prevReturn; + m_currentClassCtx = prevClass; + m_inStaticContext = prevStatic; + m_inConstructor = prevCtor; + m_inDestructor = prevDtor; + return ret; +} + +Value RuntimeEvaluator::call(FunctionDeclaration* fn, const std::vector& args) { + // Bind parameters, run the body until a return is hit, then unwind. + beginScope(); + for (size_t i = 0; i < fn->params.size() && i < args.size(); ++i) { + m_env.back()[fn->params[i]->name] = {args[i], false, true}; + } + bool prevReturn = m_hasReturn; + m_returnValue = {}; + m_hasReturn = false; + if (fn->body) { + for (auto& stmt : fn->body->statements) { + exec(stmt.get()); + if (m_hasReturn) + break; + } + } + Value ret = m_returnValue; + endScope(); + m_hasReturn = prevReturn; + return ret; +} + +void RuntimeEvaluator::exec(Statement* s) { + if (m_gcRequested.load()) + runCycleCollector(); + if (!s) + return; + auto isTruthy = [](const Value& v) { + switch (v.type) { + case Value::Type::Boolean: + return v.boolValue; + case Value::Type::Bit: + return v.bitValue != 0; + case Value::Type::Int: + return v.intValue != 0; + case Value::Type::Long: + return v.longValue != 0; + case Value::Type::Float: + return v.floatValue != 0.0; + default: + return false; + } + }; + if (auto var = dynamic_cast(s)) { + Value v; + if (auto prim = dynamic_cast(var->varType.get())) { + if (prim->name == "int") + v.type = Value::Type::Int; + else if (prim->name == "long") + v.type = Value::Type::Long; + else if (prim->name == "bit") + v.type = Value::Type::Bit; + else if (prim->name == "boolean") + v.type = Value::Type::Boolean; + else if (prim->name == "float") + v.type = Value::Type::Float; + else if (prim->name == "string") + v.type = Value::Type::String; + else if (prim->name == "char") + v.type = Value::Type::Char; + else if (prim->name == "qubit") { + v.type = Value::Type::Qubit; + v.qubit = allocateTrackedQubit(var->name); } - }; - if (auto var = dynamic_cast(s)) { - Value v; - if (auto prim = dynamic_cast(var->varType.get())) { - if (prim->name == "int") - v.type = Value::Type::Int; - else if (prim->name == "long") - v.type = Value::Type::Long; - else if (prim->name == "bit") - v.type = Value::Type::Bit; - else if (prim->name == "boolean") - v.type = Value::Type::Boolean; - else if (prim->name == "float") - v.type = Value::Type::Float; - else if (prim->name == "string") - v.type = Value::Type::String; - else if (prim->name == "char") - v.type = Value::Type::Char; - else if (prim->name == "qubit") { - v.type = Value::Type::Qubit; - v.qubit = allocateTrackedQubit(var->name); - } - } else if (auto arr = dynamic_cast(var->varType.get())) { - if (auto elem = dynamic_cast(arr->elementType.get())) { - if (elem->name == "bit") - v.type = Value::Type::BitArray; - else if (elem->name == "boolean") - v.type = Value::Type::BooleanArray; - else if (elem->name == "int") - v.type = Value::Type::IntArray; - else if (elem->name == "long") - v.type = Value::Type::LongArray; - else if (elem->name == "float") - v.type = Value::Type::FloatArray; - else if (elem->name == "string") - v.type = Value::Type::StringArray; - else if (elem->name == "char") - v.type = Value::Type::CharArray; - else if (elem->name == "qubit") - v.type = Value::Type::QubitArray; - } - if (arr->size < 0 && arr->sizeExpression) { - Value sizeVal = eval(arr->sizeExpression.get()); - if (sizeVal.type != Value::Type::Int) { - throw BlochError(ErrorCategory::Runtime, var->line, var->column, - "array size must evaluate to an int"); - } - arr->size = sizeVal.intValue; - if (arr->size < 0) { + } else if (auto arr = dynamic_cast(var->varType.get())) { + if (auto elem = dynamic_cast(arr->elementType.get())) { + if (elem->name == "bit") + v.type = Value::Type::BitArray; + else if (elem->name == "boolean") + v.type = Value::Type::BooleanArray; + else if (elem->name == "int") + v.type = Value::Type::IntArray; + else if (elem->name == "long") + v.type = Value::Type::LongArray; + else if (elem->name == "float") + v.type = Value::Type::FloatArray; + else if (elem->name == "string") + v.type = Value::Type::StringArray; + else if (elem->name == "char") + v.type = Value::Type::CharArray; + else if (elem->name == "qubit") + v.type = Value::Type::QubitArray; + } + if (arr->size < 0 && arr->sizeExpression) { + Value sizeVal = eval(arr->sizeExpression.get()); + if (sizeVal.type != Value::Type::Int) { + throw BlochError(ErrorCategory::Runtime, var->line, var->column, + "array size must evaluate to an int"); + } + arr->size = sizeVal.intValue; + if (arr->size < 0) { + throw BlochError(ErrorCategory::Runtime, var->line, var->column, + "array size must be non-negative"); + } + } + // Handle fixed-size allocation (without initializer) + if (arr->size >= 0 && !var->initializer) { + int n = arr->size; + if (v.type == Value::Type::BitArray) + v.bitArray.assign(n, 0); + else if (v.type == Value::Type::BooleanArray) + v.boolArray.assign(n, false); + else if (v.type == Value::Type::LongArray) + v.longArray.assign(n, 0); + else if (v.type == Value::Type::IntArray) + v.intArray.assign(n, 0); + else if (v.type == Value::Type::FloatArray) + v.floatArray.assign(n, 0.0); + else if (v.type == Value::Type::StringArray) + v.stringArray.assign(n, ""); + else if (v.type == Value::Type::CharArray) + v.charArray.assign(n, '\0'); + else if (v.type == Value::Type::QubitArray) { + v.qubitArray.resize(n); + for (int i = 0; i < n; ++i) + v.qubitArray[i] = allocateTrackedQubit(var->name); + } + } + } else if (dynamic_cast(var->varType.get())) { + v.type = Value::Type::Object; + } + bool initialized = false; + if (var->initializer) { + // Special case of array literal initialisation for typed arrays + if (auto arrType = dynamic_cast(var->varType.get())) { + if (auto elem = dynamic_cast(arrType->elementType.get())) { + if (elem->name == "qubit") { throw BlochError(ErrorCategory::Runtime, var->line, var->column, - "array size must be non-negative"); - } - } - // Handle fixed-size allocation (without initializer) - if (arr->size >= 0 && !var->initializer) { - int n = arr->size; - if (v.type == Value::Type::BitArray) - v.bitArray.assign(n, 0); - else if (v.type == Value::Type::BooleanArray) - v.boolArray.assign(n, false); - else if (v.type == Value::Type::LongArray) - v.longArray.assign(n, 0); - else if (v.type == Value::Type::IntArray) - v.intArray.assign(n, 0); - else if (v.type == Value::Type::FloatArray) - v.floatArray.assign(n, 0.0); - else if (v.type == Value::Type::StringArray) - v.stringArray.assign(n, ""); - else if (v.type == Value::Type::CharArray) - v.charArray.assign(n, '\0'); - else if (v.type == Value::Type::QubitArray) { - v.qubitArray.resize(n); - for (int i = 0; i < n; ++i) - v.qubitArray[i] = allocateTrackedQubit(var->name); + "qubit[] cannot be initialised"); } - } - } else if (dynamic_cast(var->varType.get())) { - v.type = Value::Type::Object; - } - bool initialized = false; - if (var->initializer) { - // Special case of array literal initialisation for typed arrays - if (auto arrType = dynamic_cast(var->varType.get())) { - if (auto elem = dynamic_cast(arrType->elementType.get())) { - if (elem->name == "qubit") { - throw BlochError(ErrorCategory::Runtime, var->line, var->column, - "qubit[] cannot be initialised"); + if (auto arrLit = + dynamic_cast(var->initializer.get())) { + // If size is specified, enforce it + if (arrType->size >= 0 && + static_cast(arrLit->elements.size()) != arrType->size) { + throw BlochError( + ErrorCategory::Runtime, var->line, var->column, + "array initialiser length does not match declared size"); } - if (auto arrLit = - dynamic_cast(var->initializer.get())) { - // If size is specified, enforce it - if (arrType->size >= 0 && - static_cast(arrLit->elements.size()) != arrType->size) { - throw BlochError( - ErrorCategory::Runtime, var->line, var->column, - "array initialiser length does not match declared size"); + if (elem->name == "bit") { + v.type = Value::Type::BitArray; + v.bitArray.clear(); + for (auto& el : arrLit->elements) { + Value ev = eval(el.get()); + if (ev.type != Value::Type::Bit) + throw BlochError(ErrorCategory::Runtime, el->line, el->column, + "bit[] initialiser expects bit elements"); + v.bitArray.push_back(ev.bitValue ? 1 : 0); } - if (elem->name == "bit") { - v.type = Value::Type::BitArray; - v.bitArray.clear(); - for (auto& el : arrLit->elements) { - Value ev = eval(el.get()); - if (ev.type != Value::Type::Bit) - throw BlochError(ErrorCategory::Runtime, el->line, - el->column, - "bit[] initialiser expects bit elements"); - v.bitArray.push_back(ev.bitValue ? 1 : 0); - } - } else if (elem->name == "boolean") { - v.type = Value::Type::BooleanArray; - v.boolArray.clear(); - for (auto& el : arrLit->elements) { - Value ev = eval(el.get()); - if (ev.type == Value::Type::Boolean) - v.boolArray.push_back(ev.boolValue); - else if (ev.type == Value::Type::Bit) - v.boolArray.push_back(ev.bitValue != 0); - else - throw BlochError( - ErrorCategory::Runtime, el->line, el->column, - "boolean[] initialiser expects boolean elements"); - } - } else if (elem->name == "int") { - v.type = Value::Type::IntArray; - v.intArray.clear(); - for (auto& el : arrLit->elements) { - Value ev = eval(el.get()); - int val = 0; - if (ev.type == Value::Type::Int) - val = ev.intValue; - else if (ev.type == Value::Type::Long) - val = static_cast(ev.longValue); - else if (ev.type == Value::Type::Bit) - val = ev.bitValue; - else if (ev.type == Value::Type::Float) - val = static_cast(ev.floatValue); - else - throw BlochError( - ErrorCategory::Runtime, el->line, el->column, - "int[] initialiser expects integer elements"); - v.intArray.push_back(val); - } - } else if (elem->name == "long") { - v.type = Value::Type::LongArray; - v.longArray.clear(); - for (auto& el : arrLit->elements) { - Value ev = eval(el.get()); - std::int64_t val = 0; - if (ev.type == Value::Type::Long) - val = ev.longValue; - else if (ev.type == Value::Type::Int) - val = ev.intValue; - else if (ev.type == Value::Type::Bit) - val = ev.bitValue; - else if (ev.type == Value::Type::Float) - val = static_cast(ev.floatValue); - else - throw BlochError( - ErrorCategory::Runtime, el->line, el->column, - "long[] initialiser expects integer elements"); - v.longArray.push_back(val); - } - } else if (elem->name == "float") { - v.type = Value::Type::FloatArray; - v.floatArray.clear(); - for (auto& el : arrLit->elements) { - Value ev = eval(el.get()); - double val = 0.0; - if (ev.type == Value::Type::Float) - val = ev.floatValue; - else if (ev.type == Value::Type::Int) - val = static_cast(ev.intValue); - else if (ev.type == Value::Type::Bit) - val = static_cast(ev.bitValue); - else - throw BlochError( - ErrorCategory::Runtime, el->line, el->column, - "float[] initialiser expects float elements"); - v.floatArray.push_back(val); - } - } else if (elem->name == "string") { - v.type = Value::Type::StringArray; - v.stringArray.clear(); - for (auto& el : arrLit->elements) { - Value ev = eval(el.get()); - if (ev.type != Value::Type::String) - throw BlochError( - ErrorCategory::Runtime, el->line, el->column, - "string[] initialiser expects string elements"); - v.stringArray.push_back(ev.stringValue); - } - } else if (elem->name == "char") { - v.type = Value::Type::CharArray; - v.charArray.clear(); - for (auto& el : arrLit->elements) { - Value ev = eval(el.get()); - if (ev.type == Value::Type::Char) - v.charArray.push_back(ev.charValue); - else - throw BlochError( - ErrorCategory::Runtime, el->line, el->column, - "char[] initialiser expects char elements"); - } + } else if (elem->name == "boolean") { + v.type = Value::Type::BooleanArray; + v.boolArray.clear(); + for (auto& el : arrLit->elements) { + Value ev = eval(el.get()); + if (ev.type == Value::Type::Boolean) + v.boolArray.push_back(ev.boolValue); + else if (ev.type == Value::Type::Bit) + v.boolArray.push_back(ev.bitValue != 0); + else + throw BlochError( + ErrorCategory::Runtime, el->line, el->column, + "boolean[] initialiser expects boolean elements"); + } + } else if (elem->name == "int") { + v.type = Value::Type::IntArray; + v.intArray.clear(); + for (auto& el : arrLit->elements) { + Value ev = eval(el.get()); + int val = 0; + if (ev.type == Value::Type::Int) + val = ev.intValue; + else if (ev.type == Value::Type::Long) + val = static_cast(ev.longValue); + else if (ev.type == Value::Type::Bit) + val = ev.bitValue; + else if (ev.type == Value::Type::Float) + val = static_cast(ev.floatValue); + else + throw BlochError(ErrorCategory::Runtime, el->line, el->column, + "int[] initialiser expects integer elements"); + v.intArray.push_back(val); + } + } else if (elem->name == "long") { + v.type = Value::Type::LongArray; + v.longArray.clear(); + for (auto& el : arrLit->elements) { + Value ev = eval(el.get()); + std::int64_t val = 0; + if (ev.type == Value::Type::Long) + val = ev.longValue; + else if (ev.type == Value::Type::Int) + val = ev.intValue; + else if (ev.type == Value::Type::Bit) + val = ev.bitValue; + else if (ev.type == Value::Type::Float) + val = static_cast(ev.floatValue); + else + throw BlochError(ErrorCategory::Runtime, el->line, el->column, + "long[] initialiser expects integer elements"); + v.longArray.push_back(val); + } + } else if (elem->name == "float") { + v.type = Value::Type::FloatArray; + v.floatArray.clear(); + for (auto& el : arrLit->elements) { + Value ev = eval(el.get()); + double val = 0.0; + if (ev.type == Value::Type::Float) + val = ev.floatValue; + else if (ev.type == Value::Type::Int) + val = static_cast(ev.intValue); + else if (ev.type == Value::Type::Bit) + val = static_cast(ev.bitValue); + else + throw BlochError(ErrorCategory::Runtime, el->line, el->column, + "float[] initialiser expects float elements"); + v.floatArray.push_back(val); + } + } else if (elem->name == "string") { + v.type = Value::Type::StringArray; + v.stringArray.clear(); + for (auto& el : arrLit->elements) { + Value ev = eval(el.get()); + if (ev.type != Value::Type::String) + throw BlochError( + ErrorCategory::Runtime, el->line, el->column, + "string[] initialiser expects string elements"); + v.stringArray.push_back(ev.stringValue); + } + } else if (elem->name == "char") { + v.type = Value::Type::CharArray; + v.charArray.clear(); + for (auto& el : arrLit->elements) { + Value ev = eval(el.get()); + if (ev.type == Value::Type::Char) + v.charArray.push_back(ev.charValue); + else + throw BlochError(ErrorCategory::Runtime, el->line, el->column, + "char[] initialiser expects char elements"); } - initialized = true; - } else { - // Fallback: evaluate as expression - v = eval(var->initializer.get()); - initialized = true; } + initialized = true; + } else { + // Fallback: evaluate as expression + v = eval(var->initializer.get()); + initialized = true; } - } else { - v = eval(var->initializer.get()); - initialized = true; } - } - m_env.back()[var->name] = {v, var->isTracked, initialized}; - } else if (auto block = dynamic_cast(s)) { - beginScope(); - for (auto& st : block->statements) { - exec(st.get()); - if (m_hasReturn) - break; - } - endScope(); - } else if (auto exprs = dynamic_cast(s)) { - eval(exprs->expression.get()); - } else if (auto ret = dynamic_cast(s)) { - if (ret->value) - m_returnValue = eval(ret->value.get()); - m_hasReturn = true; - } else if (auto ifs = dynamic_cast(s)) { - Value cond = eval(ifs->condition.get()); - if (isTruthy(cond)) { - exec(ifs->thenBranch.get()); } else { - exec(ifs->elseBranch.get()); + v = eval(var->initializer.get()); + initialized = true; } - } else if (auto tern = dynamic_cast(s)) { - Value cond = eval(tern->condition.get()); - if (isTruthy(cond)) { - exec(tern->thenBranch.get()); - } else { - exec(tern->elseBranch.get()); - } - } else if (auto fors = dynamic_cast(s)) { - beginScope(); - if (fors->initializer) - exec(fors->initializer.get()); - while (true) { - bool condVal = true; - if (fors->condition) - condVal = isTruthy(eval(fors->condition.get())); - if (!condVal) - break; - exec(fors->body.get()); - if (m_hasReturn) - break; - if (fors->increment) - eval(fors->increment.get()); - } - endScope(); - } else if (auto whiles = dynamic_cast(s)) { - while (true) { - bool condVal = true; - if (whiles->condition) - condVal = isTruthy(eval(whiles->condition.get())); - if (!condVal) - break; - exec(whiles->body.get()); - if (m_hasReturn) - break; + } + m_env.back()[var->name] = {v, var->isTracked, initialized}; + } else if (auto block = dynamic_cast(s)) { + beginScope(); + for (auto& st : block->statements) { + exec(st.get()); + if (m_hasReturn) + break; + } + endScope(); + } else if (auto exprs = dynamic_cast(s)) { + eval(exprs->expression.get()); + } else if (auto ret = dynamic_cast(s)) { + if (ret->value) + m_returnValue = eval(ret->value.get()); + m_hasReturn = true; + } else if (auto ifs = dynamic_cast(s)) { + Value cond = eval(ifs->condition.get()); + if (isTruthy(cond)) { + exec(ifs->thenBranch.get()); + } else { + exec(ifs->elseBranch.get()); + } + } else if (auto tern = dynamic_cast(s)) { + Value cond = eval(tern->condition.get()); + if (isTruthy(cond)) { + exec(tern->thenBranch.get()); + } else { + exec(tern->elseBranch.get()); + } + } else if (auto fors = dynamic_cast(s)) { + beginScope(); + if (fors->initializer) + exec(fors->initializer.get()); + while (true) { + bool condVal = true; + if (fors->condition) + condVal = isTruthy(eval(fors->condition.get())); + if (!condVal) + break; + exec(fors->body.get()); + if (m_hasReturn) + break; + if (fors->increment) + eval(fors->increment.get()); + } + endScope(); + } else if (auto whiles = dynamic_cast(s)) { + while (true) { + bool condVal = true; + if (whiles->condition) + condVal = isTruthy(eval(whiles->condition.get())); + if (!condVal) + break; + exec(whiles->body.get()); + if (m_hasReturn) + break; + } + } else if (auto echo = dynamic_cast(s)) { + Value v = eval(echo->value.get()); + if (m_echoEnabled) + m_echoBuffer.push_back(valueToString(v)); + } else if (auto reset = dynamic_cast(s)) { + Value q = eval(reset->target.get()); + ensureQubitExists(q.qubit, reset->line, reset->column); + m_sim.reset(q.qubit); + unmarkMeasured(q.qubit); + } else if (auto meas = dynamic_cast(s)) { + Value q = eval(meas->qubit.get()); + if (q.type == Value::Type::QubitArray) { + for (int idx = 0; idx < static_cast(q.qubitArray.size()); ++idx) { + int qid = q.qubitArray[idx]; + ensureQubitActive(qid, meas->line, meas->column); + int bit = m_sim.measure(qid); + markMeasured(qid); + if (qid >= 0 && qid < static_cast(m_lastMeasurement.size())) + m_lastMeasurement[qid] = bit; } - } else if (auto echo = dynamic_cast(s)) { - Value v = eval(echo->value.get()); - if (m_echoEnabled) - m_echoBuffer.push_back(valueToString(v)); - } else if (auto reset = dynamic_cast(s)) { - Value q = eval(reset->target.get()); - ensureQubitExists(q.qubit, reset->line, reset->column); - m_sim.reset(q.qubit); - unmarkMeasured(q.qubit); - } else if (auto meas = dynamic_cast(s)) { - Value q = eval(meas->qubit.get()); - if (q.type == Value::Type::QubitArray) { - for (int idx = 0; idx < static_cast(q.qubitArray.size()); ++idx) { - int qid = q.qubitArray[idx]; - ensureQubitActive(qid, meas->line, meas->column); - int bit = m_sim.measure(qid); - markMeasured(qid); - if (qid >= 0 && qid < static_cast(m_lastMeasurement.size())) - m_lastMeasurement[qid] = bit; - } - } else { - ensureQubitActive(q.qubit, meas->line, meas->column); - int bit = m_sim.measure(q.qubit); - markMeasured(q.qubit); - if (q.qubit >= 0 && q.qubit < static_cast(m_lastMeasurement.size())) - m_lastMeasurement[q.qubit] = bit; - } - } else if (auto destroy = dynamic_cast(s)) { - if (auto var = dynamic_cast(destroy->target.get())) { - assign(var->name, {}); - requestGc(); - } else if (auto mem = dynamic_cast(destroy->target.get())) { - Value obj = eval(mem->object.get()); - if (obj.type == Value::Type::Object && obj.objectValue) { - RuntimeField* field = obj.objectValue->cls - ? findInstanceField(obj.objectValue->cls, mem->member) - : nullptr; - if (field) { - if (field->offset < obj.objectValue->fields.size()) - obj.objectValue->fields[field->offset] = {}; - requestGc(); - } + } else { + ensureQubitActive(q.qubit, meas->line, meas->column); + int bit = m_sim.measure(q.qubit); + markMeasured(q.qubit); + if (q.qubit >= 0 && q.qubit < static_cast(m_lastMeasurement.size())) + m_lastMeasurement[q.qubit] = bit; + } + } else if (auto destroy = dynamic_cast(s)) { + if (auto var = dynamic_cast(destroy->target.get())) { + assign(var->name, {}); + requestGc(); + } else if (auto mem = dynamic_cast(destroy->target.get())) { + Value obj = eval(mem->object.get()); + if (obj.type == Value::Type::Object && obj.objectValue) { + RuntimeField* field = obj.objectValue->cls + ? findInstanceField(obj.objectValue->cls, mem->member) + : nullptr; + if (field) { + if (field->offset < obj.objectValue->fields.size()) + obj.objectValue->fields[field->offset] = {}; + requestGc(); } - } else { - (void)eval(destroy->target.get()); } - } else if (auto assignStmt = dynamic_cast(s)) { - Value val = eval(assignStmt->value.get()); - assign(assignStmt->name, val); + } else { + (void)eval(destroy->target.get()); } - throwDeferredRuntimeError(); + } else if (auto assignStmt = dynamic_cast(s)) { + Value val = eval(assignStmt->value.get()); + assign(assignStmt->name, val); } + throwDeferredRuntimeError(); +} - Value RuntimeEvaluator::eval(Expression* e) { - if (!e) - return {}; - if (dynamic_cast(e)) { - Value v; - v.type = Value::Type::Object; - v.objectValue = nullptr; - v.className = ""; - return v; +Value RuntimeEvaluator::eval(Expression* e) { + if (!e) + return {}; + if (dynamic_cast(e)) { + Value v; + v.type = Value::Type::Object; + v.objectValue = nullptr; + v.className = ""; + return v; + } + if (auto lit = dynamic_cast(e)) { + Value v; + if (lit->literalType == "bit") { + v.type = Value::Type::Bit; + v.bitValue = std::stoi(lit->value); + } else if (lit->literalType == "boolean") { + v.type = Value::Type::Boolean; + v.boolValue = (lit->value == "true"); + } else if (lit->literalType == "long") { + v.type = Value::Type::Long; + std::string text = lit->value; + if (!text.empty() && (text.back() == 'L' || text.back() == 'l')) + text.pop_back(); + try { + v.longValue = std::stoll(text); + } catch (...) { + v.longValue = 0; + } + } else if (lit->literalType == "float") { + v.type = Value::Type::Float; + v.floatValue = std::stof(lit->value); + } else if (lit->literalType == "string") { + v.type = Value::Type::String; + if (lit->value.size() >= 2) + v.stringValue = lit->value.substr(1, lit->value.size() - 2); + else + v.stringValue = ""; + } else if (lit->literalType == "char") { + v.type = Value::Type::Char; + if (lit->value.size() >= 3) + v.charValue = lit->value[1]; + else + v.charValue = '\0'; + } else { + v.type = Value::Type::Int; + v.intValue = std::stoi(lit->value); } - if (auto lit = dynamic_cast(e)) { - Value v; - if (lit->literalType == "bit") { - v.type = Value::Type::Bit; - v.bitValue = std::stoi(lit->value); - } else if (lit->literalType == "boolean") { - v.type = Value::Type::Boolean; - v.boolValue = (lit->value == "true"); - } else if (lit->literalType == "long") { - v.type = Value::Type::Long; - std::string text = lit->value; - if (!text.empty() && (text.back() == 'L' || text.back() == 'l')) - text.pop_back(); - try { - v.longValue = std::stoll(text); - } catch (...) { - v.longValue = 0; - } - } else if (lit->literalType == "float") { - v.type = Value::Type::Float; - v.floatValue = std::stof(lit->value); - } else if (lit->literalType == "string") { - v.type = Value::Type::String; - if (lit->value.size() >= 2) - v.stringValue = lit->value.substr(1, lit->value.size() - 2); - else - v.stringValue = ""; - } else if (lit->literalType == "char") { - v.type = Value::Type::Char; - if (lit->value.size() >= 3) - v.charValue = lit->value[1]; - else - v.charValue = '\0'; - } else { + return v; + } else if (auto paren = dynamic_cast(e)) { + return eval(paren->expression.get()); + } else if (auto cast = dynamic_cast(e)) { + Value in = eval(cast->expression.get()); + RuntimeTypeInfo target = typeInfoFromAst(cast->targetType.get()); + switch (target.kind) { + case Value::Type::Int: { + Value v; v.type = Value::Type::Int; - v.intValue = std::stoi(lit->value); - } - return v; - } else if (auto paren = dynamic_cast(e)) { - return eval(paren->expression.get()); - } else if (auto cast = dynamic_cast(e)) { - Value in = eval(cast->expression.get()); - RuntimeTypeInfo target = typeInfoFromAst(cast->targetType.get()); - switch (target.kind) { - case Value::Type::Int: { - Value v; - v.type = Value::Type::Int; - if (in.type == Value::Type::Int) { - v.intValue = in.intValue; - return v; - } - if (in.type == Value::Type::Long) { - v.intValue = static_cast(in.longValue); - return v; - } - if (in.type == Value::Type::Bit) { - v.intValue = in.bitValue; - return v; - } - if (in.type == Value::Type::Float) { - v.intValue = static_cast(in.floatValue); - return v; - } - if (in.type == Value::Type::Char) { - v.intValue = static_cast(in.charValue); - return v; - } - break; + if (in.type == Value::Type::Int) { + v.intValue = in.intValue; + return v; } - case Value::Type::Long: { - Value v; - v.type = Value::Type::Long; - if (in.type == Value::Type::Long) { - v.longValue = in.longValue; - return v; - } - if (in.type == Value::Type::Int) { - v.longValue = in.intValue; - return v; - } - if (in.type == Value::Type::Bit) { - v.longValue = in.bitValue; - return v; - } - if (in.type == Value::Type::Float) { - v.longValue = static_cast(in.floatValue); - return v; - } - if (in.type == Value::Type::Char) { - v.longValue = static_cast(in.charValue); - return v; - } - break; + if (in.type == Value::Type::Long) { + v.intValue = static_cast(in.longValue); + return v; } - case Value::Type::Float: { - Value v; - v.type = Value::Type::Float; - if (in.type == Value::Type::Float) { - v.floatValue = in.floatValue; - return v; - } - if (in.type == Value::Type::Int) { - v.floatValue = static_cast(in.intValue); - return v; - } - if (in.type == Value::Type::Long) { - v.floatValue = static_cast(in.longValue); - return v; - } - if (in.type == Value::Type::Bit) { - v.floatValue = static_cast(in.bitValue); - return v; - } - if (in.type == Value::Type::Char) { - v.floatValue = static_cast(in.charValue); - return v; - } - break; + if (in.type == Value::Type::Bit) { + v.intValue = in.bitValue; + return v; } - case Value::Type::Bit: { - Value v; - v.type = Value::Type::Bit; - if (in.type == Value::Type::Bit) { - v.bitValue = in.bitValue; - return v; - } - if (in.type == Value::Type::Int) { - v.bitValue = in.intValue != 0 ? 1 : 0; - return v; - } - if (in.type == Value::Type::Long) { - v.bitValue = in.longValue != 0 ? 1 : 0; - return v; - } - if (in.type == Value::Type::Float) { - v.bitValue = in.floatValue != 0.0 ? 1 : 0; - return v; - } - break; + if (in.type == Value::Type::Float) { + v.intValue = static_cast(in.floatValue); + return v; } - case Value::Type::Char: { - Value v; - v.type = Value::Type::Char; - if (in.type == Value::Type::Char) { - v.charValue = in.charValue; - return v; - } - if (in.type == Value::Type::Int) { - v.charValue = static_cast(in.intValue); - return v; - } - if (in.type == Value::Type::Long) { - v.charValue = static_cast(in.longValue); - return v; - } - break; + if (in.type == Value::Type::Char) { + v.intValue = static_cast(in.charValue); + return v; } - default: - break; - } - throw BlochError(ErrorCategory::Runtime, cast->line, cast->column, - "invalid cast operation"); - } else if (auto var = dynamic_cast(e)) { - return lookup(var->name); - } else if (auto arr = dynamic_cast(e)) { - // Infer array type from first element (if present) - Value v; - if (arr->elements.empty()) { - v.type = Value::Type::IntArray; - return v; // empty, default as int[] when untyped - } - Value first = eval(arr->elements[0].get()); - switch (first.type) { - case Value::Type::Bit: - v.type = Value::Type::BitArray; - for (auto& el : arr->elements) { - Value ev = eval(el.get()); - if (ev.type != Value::Type::Bit) - throw BlochError(ErrorCategory::Runtime, el->line, el->column, - "inconsistent element types in array literal"); - v.bitArray.push_back(ev.bitValue ? 1 : 0); - } - break; - case Value::Type::Boolean: - v.type = Value::Type::BooleanArray; - for (auto& el : arr->elements) { - Value ev = eval(el.get()); - if (ev.type != Value::Type::Boolean) - throw BlochError(ErrorCategory::Runtime, el->line, el->column, - "inconsistent element types in array literal"); - v.boolArray.push_back(ev.boolValue); - } - break; - case Value::Type::Int: - v.type = Value::Type::IntArray; - for (auto& el : arr->elements) { - Value ev = eval(el.get()); - if (ev.type != Value::Type::Int && ev.type != Value::Type::Bit) - throw BlochError(ErrorCategory::Runtime, el->line, el->column, - "inconsistent element types in array literal"); - v.intArray.push_back(ev.type == Value::Type::Int ? ev.intValue - : ev.bitValue); - } - break; - case Value::Type::Long: - v.type = Value::Type::LongArray; - for (auto& el : arr->elements) { - Value ev = eval(el.get()); - if (ev.type != Value::Type::Long && ev.type != Value::Type::Int && - ev.type != Value::Type::Bit) - throw BlochError(ErrorCategory::Runtime, el->line, el->column, - "inconsistent element types in array literal"); - std::int64_t val = - ev.type == Value::Type::Long - ? ev.longValue - : static_cast( - ev.type == Value::Type::Int ? ev.intValue : ev.bitValue); - v.longArray.push_back(val); - } - break; - case Value::Type::Float: - v.type = Value::Type::FloatArray; - for (auto& el : arr->elements) { - Value ev = eval(el.get()); - if (ev.type != Value::Type::Float && ev.type != Value::Type::Int && - ev.type != Value::Type::Long && ev.type != Value::Type::Bit) - throw BlochError(ErrorCategory::Runtime, el->line, el->column, - "inconsistent element types in array literal"); - double val = (ev.type == Value::Type::Float) - ? ev.floatValue - : static_cast(ev.type == Value::Type::Int - ? ev.intValue - : (ev.type == Value::Type::Long - ? ev.longValue - : ev.bitValue)); - v.floatArray.push_back(val); - } - break; - case Value::Type::String: - v.type = Value::Type::StringArray; - for (auto& el : arr->elements) { - Value ev = eval(el.get()); - if (ev.type != Value::Type::String) - throw BlochError(ErrorCategory::Runtime, el->line, el->column, - "inconsistent element types in array literal"); - v.stringArray.push_back(ev.stringValue); - } - break; - case Value::Type::Char: - v.type = Value::Type::CharArray; - for (auto& el : arr->elements) { - Value ev = eval(el.get()); - if (ev.type != Value::Type::Char) - throw BlochError(ErrorCategory::Runtime, el->line, el->column, - "inconsistent element types in array literal"); - v.charArray.push_back(ev.charValue); - } - break; - default: - throw BlochError(ErrorCategory::Runtime, arr->line, arr->column, - "unsupported array literal type"); - } - return v; - } else if (dynamic_cast(e)) { - return lookup("this"); - } else if (auto superExpr = dynamic_cast(e)) { - (void)superExpr; - Value v; - v.type = Value::Type::ClassRef; - if (m_currentClassCtx && m_currentClassCtx->base) { - v.classRef = m_currentClassCtx->base; - v.className = m_currentClassCtx->base->name; + break; } - return v; - } else if (auto newExpr = dynamic_cast(e)) { - std::unordered_map subst; - if (m_currentClassCtx && !m_currentClassCtx->typeParamNames.empty()) { - for (size_t i = 0; i < m_currentClassCtx->typeParamNames.size() && - i < m_currentClassCtx->typeArgs.size(); - ++i) { - subst[m_currentClassCtx->typeParamNames[i]] = m_currentClassCtx->typeArgs[i]; + case Value::Type::Long: { + Value v; + v.type = Value::Type::Long; + if (in.type == Value::Type::Long) { + v.longValue = in.longValue; + return v; } - } - RuntimeTypeInfo tinfo = typeInfoFromAst(newExpr->classType.get(), subst); - RuntimeClass* cls = findClass(tinfo.className); - if (!cls) { - if (auto named = dynamic_cast(newExpr->classType.get())) - cls = instantiateGeneric(named, subst); - } - if (!cls) - throw BlochError(ErrorCategory::Runtime, newExpr->line, newExpr->column, - "class '" + tinfo.className + "' not found"); - if (cls->isStatic || cls->isAbstract) { - throw BlochError(ErrorCategory::Runtime, newExpr->line, newExpr->column, - "cannot instantiate static or abstract class '" + cls->name + "'"); - } - auto deleter = [this](Object* obj) { - // This try/catch means that user error in custom destructors is handled internally - // and does not crash the application - try { - destroyObject(obj, !obj->skipDestructor); - } catch (...) { - deferRuntimeError(std::current_exception()); + if (in.type == Value::Type::Int) { + v.longValue = in.intValue; + return v; } - delete obj; - }; - auto obj = std::shared_ptr(new Object{}, deleter); - obj->cls = cls; - obj->owner = this; - obj->fields.assign(cls->instanceFields.size(), {}); - for (auto& f : cls->instanceFields) { - if (!f.isStatic && f.offset < obj->fields.size()) - obj->fields[f.offset] = defaultValueForField(f, cls->name); - } - { - std::lock_guard lock(m_heapMutex); - m_heap.push_back(obj); - } - std::vector args; - for (auto& a : newExpr->arguments) args.push_back(eval(a.get())); - ConstructorDeclaration* ctorDecl = nullptr; - bool matchedCtor = false; - bool ambiguousCtor = false; - int bestCost = std::numeric_limits::max(); - for (auto& c : cls->constructors) { - auto cost = argumentsConversionCost(c.params, args); - if (!cost) - continue; - if (*cost < bestCost) { - bestCost = *cost; - ctorDecl = c.decl; - matchedCtor = true; - ambiguousCtor = false; - } else if (*cost == bestCost) { - ambiguousCtor = true; + if (in.type == Value::Type::Bit) { + v.longValue = in.bitValue; + return v; } + if (in.type == Value::Type::Float) { + v.longValue = static_cast(in.floatValue); + return v; + } + if (in.type == Value::Type::Char) { + v.longValue = static_cast(in.charValue); + return v; + } + break; } - if (!matchedCtor) { - throw BlochError(ErrorCategory::Runtime, newExpr->line, newExpr->column, - "no constructor matches provided arguments"); - } - if (ambiguousCtor) { - throw BlochError(ErrorCategory::Runtime, newExpr->line, newExpr->column, - "ambiguous constructor matches provided arguments"); - } - if (kTraceConstructors) { - std::cerr << "[new] " << cls->name << " selected ctor params=" << args.size() - << std::endl; - } - runConstructorChain(cls, obj, ctorDecl, args); - Value v; - v.type = Value::Type::Object; - v.objectValue = obj; - v.className = cls->name; - ++m_allocSinceGc; - if (m_allocSinceGc > 16) - requestGc(); - return v; - } else if (auto memAcc = dynamic_cast(e)) { - Value obj = eval(memAcc->object.get()); - if (isNullReference(obj)) { - throw BlochError(ErrorCategory::Runtime, memAcc->line, memAcc->column, - "null reference"); - } - if (obj.type == Value::Type::ClassRef && obj.classRef) { - auto [field, owner] = findStaticFieldWithOwner(obj.classRef, memAcc->member); - RuntimeMethod* method = findMethod(obj.classRef, memAcc->member); - if (field && owner) { - size_t idx = field->offset; - if (idx < owner->staticStorage.size()) - return owner->staticStorage[idx]; - } else if (method) { - Value v; - v.type = Value::Type::ClassRef; - v.classRef = obj.classRef; - v.className = obj.classRef->name; + case Value::Type::Float: { + Value v; + v.type = Value::Type::Float; + if (in.type == Value::Type::Float) { + v.floatValue = in.floatValue; + return v; + } + if (in.type == Value::Type::Int) { + v.floatValue = static_cast(in.intValue); return v; } - throw BlochError(ErrorCategory::Runtime, memAcc->line, memAcc->column, - "member not found on class"); + if (in.type == Value::Type::Long) { + v.floatValue = static_cast(in.longValue); + return v; + } + if (in.type == Value::Type::Bit) { + v.floatValue = static_cast(in.bitValue); + return v; + } + if (in.type == Value::Type::Char) { + v.floatValue = static_cast(in.charValue); + return v; + } + break; } - if (obj.type == Value::Type::Object && obj.objectValue) { - RuntimeField* instField = - obj.objectValue->cls ? findInstanceField(obj.objectValue->cls, memAcc->member) - : nullptr; - if (instField) { - if (instField->offset < obj.objectValue->fields.size()) - return obj.objectValue->fields[instField->offset]; - } else { - auto [staticField, owner] = - obj.objectValue->cls - ? findStaticFieldWithOwner(obj.objectValue->cls, memAcc->member) - : std::pair{nullptr, nullptr}; - if (staticField && owner && staticField->offset < owner->staticStorage.size()) - return owner->staticStorage[staticField->offset]; + case Value::Type::Bit: { + Value v; + v.type = Value::Type::Bit; + if (in.type == Value::Type::Bit) { + v.bitValue = in.bitValue; + return v; + } + if (in.type == Value::Type::Int) { + v.bitValue = in.intValue != 0 ? 1 : 0; + return v; + } + if (in.type == Value::Type::Long) { + v.bitValue = in.longValue != 0 ? 1 : 0; + return v; } + if (in.type == Value::Type::Float) { + v.bitValue = in.floatValue != 0.0 ? 1 : 0; + return v; + } + break; } - return {}; - } else if (auto bin = dynamic_cast(e)) { - Value l = eval(bin->left.get()); - Value r = eval(bin->right.get()); - auto isObjectLike = [](const Value& v) { - return v.type == Value::Type::Object || v.type == Value::Type::ClassRef; - }; - auto makeBoolean = [](bool b) { + case Value::Type::Char: { Value v; - v.type = Value::Type::Boolean; - v.boolValue = b; - return v; - }; - - if (bin->op == "==" || bin->op == "!=") { - if (isObjectLike(l) || isObjectLike(r)) { - if (l.type == Value::Type::Object && r.type == Value::Type::Object) { - bool eq = l.objectValue == r.objectValue; - bool res = (bin->op == "==") ? eq : !eq; - return makeBoolean(res); - } - if (l.type == Value::Type::ClassRef && r.type == Value::Type::ClassRef) { - bool eq = l.classRef == r.classRef; - bool res = (bin->op == "==") ? eq : !eq; - return makeBoolean(res); - } - throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, - "equality on references requires two class references"); + v.type = Value::Type::Char; + if (in.type == Value::Type::Char) { + v.charValue = in.charValue; + return v; } - if (l.type == Value::Type::String || r.type == Value::Type::String) { - if (l.type != Value::Type::String || r.type != Value::Type::String) { - throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, - "equality requires two strings"); - } - bool eq = l.stringValue == r.stringValue; - return makeBoolean(bin->op == "==" ? eq : !eq); + if (in.type == Value::Type::Int) { + v.charValue = static_cast(in.intValue); + return v; } - if (l.type == Value::Type::Char || r.type == Value::Type::Char) { - if (l.type != Value::Type::Char || r.type != Value::Type::Char) { - throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, - "equality requires two chars"); - } - bool eq = l.charValue == r.charValue; - return makeBoolean(bin->op == "==" ? eq : !eq); + if (in.type == Value::Type::Long) { + v.charValue = static_cast(in.longValue); + return v; } + break; } - - bool lIsBool = l.type == Value::Type::Boolean; - bool rIsBool = r.type == Value::Type::Boolean; - if (lIsBool || rIsBool) { - auto toBool = [&](const Value& v) -> bool { - if (v.type == Value::Type::Boolean) - return v.boolValue; - if (v.type == Value::Type::Bit) - return v.bitValue != 0; - throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, - "boolean operations require boolean or bit operands"); - }; - if (bin->op == "&&" || bin->op == "||") { - bool lb = toBool(l); - bool rb = toBool(r); - return makeBoolean(bin->op == "&&" ? (lb && rb) : (lb || rb)); + default: + break; + } + throw BlochError(ErrorCategory::Runtime, cast->line, cast->column, + "invalid cast operation"); + } else if (auto var = dynamic_cast(e)) { + return lookup(var->name); + } else if (auto arr = dynamic_cast(e)) { + // Infer array type from first element (if present) + Value v; + if (arr->elements.empty()) { + v.type = Value::Type::IntArray; + return v; // empty, default as int[] when untyped + } + Value first = eval(arr->elements[0].get()); + switch (first.type) { + case Value::Type::Bit: + v.type = Value::Type::BitArray; + for (auto& el : arr->elements) { + Value ev = eval(el.get()); + if (ev.type != Value::Type::Bit) + throw BlochError(ErrorCategory::Runtime, el->line, el->column, + "inconsistent element types in array literal"); + v.bitArray.push_back(ev.bitValue ? 1 : 0); } - if (bin->op == "==" || bin->op == "!=") { - bool lb = toBool(l); - bool rb = toBool(r); - return makeBoolean(bin->op == "==" ? (lb == rb) : (lb != rb)); + break; + case Value::Type::Boolean: + v.type = Value::Type::BooleanArray; + for (auto& el : arr->elements) { + Value ev = eval(el.get()); + if (ev.type != Value::Type::Boolean) + throw BlochError(ErrorCategory::Runtime, el->line, el->column, + "inconsistent element types in array literal"); + v.boolArray.push_back(ev.boolValue); } - throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, - "operator '" + bin->op + "' not supported for boolean"); - } - - auto toInt64 = [](const Value& v) -> std::int64_t { - switch (v.type) { - case Value::Type::Long: - return v.longValue; - case Value::Type::Int: - return v.intValue; - case Value::Type::Bit: - return v.bitValue; - default: - return 0; + break; + case Value::Type::Int: + v.type = Value::Type::IntArray; + for (auto& el : arr->elements) { + Value ev = eval(el.get()); + if (ev.type != Value::Type::Int && ev.type != Value::Type::Bit) + throw BlochError(ErrorCategory::Runtime, el->line, el->column, + "inconsistent element types in array literal"); + v.intArray.push_back(ev.type == Value::Type::Int ? ev.intValue : ev.bitValue); } - }; - std::int64_t lInt = toInt64(l); - std::int64_t rInt = toInt64(r); - bool hasFloat = l.type == Value::Type::Float || r.type == Value::Type::Float; - bool hasLong = l.type == Value::Type::Long || r.type == Value::Type::Long; - double lNum = l.type == Value::Type::Float ? l.floatValue : static_cast(lInt); - double rNum = r.type == Value::Type::Float ? r.floatValue : static_cast(rInt); - if (bin->op == "+") { - if (l.type == Value::Type::String || r.type == Value::Type::String) { - return {Value::Type::String, 0, 0.0, 0, valueToString(l) + valueToString(r)}; + break; + case Value::Type::Long: + v.type = Value::Type::LongArray; + for (auto& el : arr->elements) { + Value ev = eval(el.get()); + if (ev.type != Value::Type::Long && ev.type != Value::Type::Int && + ev.type != Value::Type::Bit) + throw BlochError(ErrorCategory::Runtime, el->line, el->column, + "inconsistent element types in array literal"); + std::int64_t val = + ev.type == Value::Type::Long + ? ev.longValue + : static_cast(ev.type == Value::Type::Int ? ev.intValue + : ev.bitValue); + v.longArray.push_back(val); } - if (isObjectLike(l) || isObjectLike(r)) { - throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, - "operator '+' not supported for class references"); + break; + case Value::Type::Float: + v.type = Value::Type::FloatArray; + for (auto& el : arr->elements) { + Value ev = eval(el.get()); + if (ev.type != Value::Type::Float && ev.type != Value::Type::Int && + ev.type != Value::Type::Long && ev.type != Value::Type::Bit) + throw BlochError(ErrorCategory::Runtime, el->line, el->column, + "inconsistent element types in array literal"); + double val = (ev.type == Value::Type::Float) + ? ev.floatValue + : static_cast(ev.type == Value::Type::Int + ? ev.intValue + : (ev.type == Value::Type::Long + ? ev.longValue + : ev.bitValue)); + v.floatArray.push_back(val); } - if (hasFloat) { - return {Value::Type::Float, 0, lNum + rNum}; + break; + case Value::Type::String: + v.type = Value::Type::StringArray; + for (auto& el : arr->elements) { + Value ev = eval(el.get()); + if (ev.type != Value::Type::String) + throw BlochError(ErrorCategory::Runtime, el->line, el->column, + "inconsistent element types in array literal"); + v.stringArray.push_back(ev.stringValue); } - if (hasLong) { - Value v; - v.type = Value::Type::Long; - v.longValue = lInt + rInt; - return v; + break; + case Value::Type::Char: + v.type = Value::Type::CharArray; + for (auto& el : arr->elements) { + Value ev = eval(el.get()); + if (ev.type != Value::Type::Char) + throw BlochError(ErrorCategory::Runtime, el->line, el->column, + "inconsistent element types in array literal"); + v.charArray.push_back(ev.charValue); } - return {Value::Type::Int, static_cast(lInt + rInt)}; + break; + default: + throw BlochError(ErrorCategory::Runtime, arr->line, arr->column, + "unsupported array literal type"); + } + return v; + } else if (dynamic_cast(e)) { + return lookup("this"); + } else if (auto superExpr = dynamic_cast(e)) { + (void)superExpr; + Value v; + v.type = Value::Type::ClassRef; + if (m_currentClassCtx && m_currentClassCtx->base) { + v.classRef = m_currentClassCtx->base; + v.className = m_currentClassCtx->base->name; + } + return v; + } else if (auto newExpr = dynamic_cast(e)) { + std::unordered_map subst; + if (m_currentClassCtx && !m_currentClassCtx->typeParamNames.empty()) { + for (size_t i = 0; i < m_currentClassCtx->typeParamNames.size() && + i < m_currentClassCtx->typeArgs.size(); + ++i) { + subst[m_currentClassCtx->typeParamNames[i]] = m_currentClassCtx->typeArgs[i]; + } + } + RuntimeTypeInfo tinfo = typeInfoFromAst(newExpr->classType.get(), subst); + RuntimeClass* cls = findClass(tinfo.className); + if (!cls) { + if (auto named = dynamic_cast(newExpr->classType.get())) + cls = instantiateGeneric(named, subst); + } + if (!cls) + throw BlochError(ErrorCategory::Runtime, newExpr->line, newExpr->column, + "class '" + tinfo.className + "' not found"); + if (cls->isStatic || cls->isAbstract) { + throw BlochError(ErrorCategory::Runtime, newExpr->line, newExpr->column, + "cannot instantiate static or abstract class '" + cls->name + "'"); + } + auto deleter = [this](Object* obj) { + // This try/catch means that user error in custom destructors is handled internally + // and does not crash the application + try { + destroyObject(obj, !obj->skipDestructor); + } catch (...) { + deferRuntimeError(std::current_exception()); + } + delete obj; + }; + auto obj = std::shared_ptr(new Object{}, deleter); + obj->cls = cls; + obj->owner = this; + obj->fields.assign(cls->instanceFields.size(), {}); + for (auto& f : cls->instanceFields) { + if (!f.isStatic && f.offset < obj->fields.size()) + obj->fields[f.offset] = defaultValueForField(f, cls->name); + } + { + std::lock_guard lock(m_heapMutex); + m_heap.push_back(obj); + } + std::vector args; + for (auto& a : newExpr->arguments) + args.push_back(eval(a.get())); + ConstructorDeclaration* ctorDecl = nullptr; + bool matchedCtor = false; + bool ambiguousCtor = false; + int bestCost = std::numeric_limits::max(); + for (auto& c : cls->constructors) { + auto cost = argumentsConversionCost(c.params, args); + if (!cost) + continue; + if (*cost < bestCost) { + bestCost = *cost; + ctorDecl = c.decl; + matchedCtor = true; + ambiguousCtor = false; + } else if (*cost == bestCost) { + ambiguousCtor = true; } + } + if (!matchedCtor) { + throw BlochError(ErrorCategory::Runtime, newExpr->line, newExpr->column, + "no constructor matches provided arguments"); + } + if (ambiguousCtor) { + throw BlochError(ErrorCategory::Runtime, newExpr->line, newExpr->column, + "ambiguous constructor matches provided arguments"); + } + if (kTraceConstructors) { + std::cerr << "[new] " << cls->name << " selected ctor params=" << args.size() + << std::endl; + } + runConstructorChain(cls, obj, ctorDecl, args); + Value v; + v.type = Value::Type::Object; + v.objectValue = obj; + v.className = cls->name; + ++m_allocSinceGc; + if (m_allocSinceGc > 16) + requestGc(); + return v; + } else if (auto memAcc = dynamic_cast(e)) { + Value obj = eval(memAcc->object.get()); + if (isNullReference(obj)) { + throw BlochError(ErrorCategory::Runtime, memAcc->line, memAcc->column, + "null reference"); + } + if (obj.type == Value::Type::ClassRef && obj.classRef) { + auto [field, owner] = findStaticFieldWithOwner(obj.classRef, memAcc->member); + RuntimeMethod* method = findMethod(obj.classRef, memAcc->member); + if (field && owner) { + size_t idx = field->offset; + if (idx < owner->staticStorage.size()) + return owner->staticStorage[idx]; + } else if (method) { + Value v; + v.type = Value::Type::ClassRef; + v.classRef = obj.classRef; + v.className = obj.classRef->name; + return v; + } + throw BlochError(ErrorCategory::Runtime, memAcc->line, memAcc->column, + "member not found on class"); + } + if (obj.type == Value::Type::Object && obj.objectValue) { + RuntimeField* instField = obj.objectValue->cls + ? findInstanceField(obj.objectValue->cls, memAcc->member) + : nullptr; + if (instField) { + if (instField->offset < obj.objectValue->fields.size()) + return obj.objectValue->fields[instField->offset]; + } else { + auto [staticField, owner] = + obj.objectValue->cls + ? findStaticFieldWithOwner(obj.objectValue->cls, memAcc->member) + : std::pair{nullptr, nullptr}; + if (staticField && owner && staticField->offset < owner->staticStorage.size()) + return owner->staticStorage[staticField->offset]; + } + } + return {}; + } else if (auto bin = dynamic_cast(e)) { + Value l = eval(bin->left.get()); + Value r = eval(bin->right.get()); + auto isObjectLike = [](const Value& v) { + return v.type == Value::Type::Object || v.type == Value::Type::ClassRef; + }; + auto makeBoolean = [](bool b) { + Value v; + v.type = Value::Type::Boolean; + v.boolValue = b; + return v; + }; + + if (bin->op == "==" || bin->op == "!=") { if (isObjectLike(l) || isObjectLike(r)) { + if (l.type == Value::Type::Object && r.type == Value::Type::Object) { + bool eq = l.objectValue == r.objectValue; + bool res = (bin->op == "==") ? eq : !eq; + return makeBoolean(res); + } + if (l.type == Value::Type::ClassRef && r.type == Value::Type::ClassRef) { + bool eq = l.classRef == r.classRef; + bool res = (bin->op == "==") ? eq : !eq; + return makeBoolean(res); + } throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, - "operator '" + bin->op + "' not supported for class references"); + "equality on references requires two class references"); } - if (bin->op == "-") { - if (hasFloat) - return {Value::Type::Float, 0, lNum - rNum}; - if (hasLong) { - Value v; - v.type = Value::Type::Long; - v.longValue = lInt - rInt; - return v; + if (l.type == Value::Type::String || r.type == Value::Type::String) { + if (l.type != Value::Type::String || r.type != Value::Type::String) { + throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, + "equality requires two strings"); } - return {Value::Type::Int, static_cast(lInt - rInt)}; + bool eq = l.stringValue == r.stringValue; + return makeBoolean(bin->op == "==" ? eq : !eq); } - if (bin->op == "*") { - if (hasFloat) - return {Value::Type::Float, 0, lNum * rNum}; - if (hasLong) { - Value v; - v.type = Value::Type::Long; - v.longValue = lInt * rInt; - return v; + if (l.type == Value::Type::Char || r.type == Value::Type::Char) { + if (l.type != Value::Type::Char || r.type != Value::Type::Char) { + throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, + "equality requires two chars"); } - return {Value::Type::Int, static_cast(lInt * rInt)}; + bool eq = l.charValue == r.charValue; + return makeBoolean(bin->op == "==" ? eq : !eq); + } + } + + bool lIsBool = l.type == Value::Type::Boolean; + bool rIsBool = r.type == Value::Type::Boolean; + if (lIsBool || rIsBool) { + auto toBool = [&](const Value& v) -> bool { + if (v.type == Value::Type::Boolean) + return v.boolValue; + if (v.type == Value::Type::Bit) + return v.bitValue != 0; + throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, + "boolean operations require boolean or bit operands"); + }; + if (bin->op == "&&" || bin->op == "||") { + bool lb = toBool(l); + bool rb = toBool(r); + return makeBoolean(bin->op == "&&" ? (lb && rb) : (lb || rb)); + } + if (bin->op == "==" || bin->op == "!=") { + bool lb = toBool(l); + bool rb = toBool(r); + return makeBoolean(bin->op == "==" ? (lb == rb) : (lb != rb)); + } + throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, + "operator '" + bin->op + "' not supported for boolean"); + } + + auto toInt64 = [](const Value& v) -> std::int64_t { + switch (v.type) { + case Value::Type::Long: + return v.longValue; + case Value::Type::Int: + return v.intValue; + case Value::Type::Bit: + return v.bitValue; + default: + return 0; + } + }; + std::int64_t lInt = toInt64(l); + std::int64_t rInt = toInt64(r); + bool hasFloat = l.type == Value::Type::Float || r.type == Value::Type::Float; + bool hasLong = l.type == Value::Type::Long || r.type == Value::Type::Long; + double lNum = l.type == Value::Type::Float ? l.floatValue : static_cast(lInt); + double rNum = r.type == Value::Type::Float ? r.floatValue : static_cast(rInt); + if (bin->op == "+") { + if (l.type == Value::Type::String || r.type == Value::Type::String) { + return {Value::Type::String, 0, 0.0, 0, valueToString(l) + valueToString(r)}; + } + if (isObjectLike(l) || isObjectLike(r)) { + throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, + "operator '+' not supported for class references"); + } + if (hasFloat) { + return {Value::Type::Float, 0, lNum + rNum}; + } + if (hasLong) { + Value v; + v.type = Value::Type::Long; + v.longValue = lInt + rInt; + return v; + } + return {Value::Type::Int, static_cast(lInt + rInt)}; + } + if (isObjectLike(l) || isObjectLike(r)) { + throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, + "operator '" + bin->op + "' not supported for class references"); + } + if (bin->op == "-") { + if (hasFloat) + return {Value::Type::Float, 0, lNum - rNum}; + if (hasLong) { + Value v; + v.type = Value::Type::Long; + v.longValue = lInt - rInt; + return v; + } + return {Value::Type::Int, static_cast(lInt - rInt)}; + } + if (bin->op == "*") { + if (hasFloat) + return {Value::Type::Float, 0, lNum * rNum}; + if (hasLong) { + Value v; + v.type = Value::Type::Long; + v.longValue = lInt * rInt; + return v; + } + return {Value::Type::Int, static_cast(lInt * rInt)}; + } + if (bin->op == "/") { + if (rNum == 0) { + throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, + "division by zero"); + } + return {Value::Type::Float, 0, lNum / rNum}; + } + if (bin->op == "%") { + if (rInt == 0) { + throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, "modulo by zero"); + } + if (hasLong) { + Value v; + v.type = Value::Type::Long; + v.longValue = lInt % rInt; + return v; } - if (bin->op == "/") { - if (rNum == 0) { + return {Value::Type::Int, static_cast(lInt % rInt)}; + } + + if (bin->op == ">") { + if (hasFloat) + return makeBoolean(lNum > rNum); + return makeBoolean(lInt > rInt); + } + if (bin->op == "<") { + if (hasFloat) + return makeBoolean(lNum < rNum); + return makeBoolean(lInt < rInt); + } + if (bin->op == ">=") { + if (hasFloat) + return makeBoolean(lNum >= rNum); + return makeBoolean(lInt >= rInt); + } + if (bin->op == "<=") { + if (hasFloat) + return makeBoolean(lNum <= rNum); + return makeBoolean(lInt <= rInt); + } + if (bin->op == "==") { + if (hasFloat) + return makeBoolean(lNum == rNum); + return makeBoolean(lInt == rInt); + } + if (bin->op == "!=") { + if (hasFloat) + return makeBoolean(lNum != rNum); + return makeBoolean(lInt != rInt); + } + if (bin->op == "&&") { + bool lb = l.type == Value::Type::Float ? lNum != 0.0 : lInt != 0; + bool rb = r.type == Value::Type::Float ? rNum != 0.0 : rInt != 0; + return makeBoolean(lb && rb); + } + if (bin->op == "||") { + bool lb = l.type == Value::Type::Float ? lNum != 0.0 : lInt != 0; + bool rb = r.type == Value::Type::Float ? rNum != 0.0 : rInt != 0; + return makeBoolean(lb || rb); + } + if (bin->op == "&") { + if (l.type == Value::Type::Bit && r.type == Value::Type::Bit) + return {Value::Type::Bit, 0, 0.0, l.bitValue & r.bitValue}; + if (l.type == Value::Type::BitArray && r.type == Value::Type::BitArray) { + if (l.bitArray.size() != r.bitArray.size()) { throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, - "division by zero"); + "bit arrays must be same length for '&'"); } - return {Value::Type::Float, 0, lNum / rNum}; + Value v; + v.type = Value::Type::BitArray; + v.bitArray.resize(l.bitArray.size()); + for (size_t i = 0; i < l.bitArray.size(); ++i) + v.bitArray[i] = l.bitArray[i] & r.bitArray[i]; + return v; + } + if (l.type == Value::Type::BitArray && r.type == Value::Type::Bit) { + Value v; + v.type = Value::Type::BitArray; + v.bitArray.resize(l.bitArray.size()); + for (size_t i = 0; i < l.bitArray.size(); ++i) + v.bitArray[i] = l.bitArray[i] & r.bitValue; + return v; + } + if (l.type == Value::Type::Bit && r.type == Value::Type::BitArray) { + Value v; + v.type = Value::Type::BitArray; + v.bitArray.resize(r.bitArray.size()); + for (size_t i = 0; i < r.bitArray.size(); ++i) + v.bitArray[i] = l.bitValue & r.bitArray[i]; + return v; } - if (bin->op == "%") { - if (rInt == 0) { + throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, + "bitwise '&' requires bit or bit[] operands"); + } + if (bin->op == "|") { + if (l.type == Value::Type::Bit && r.type == Value::Type::Bit) + return {Value::Type::Bit, 0, 0.0, l.bitValue | r.bitValue}; + if (l.type == Value::Type::BitArray && r.type == Value::Type::BitArray) { + if (l.bitArray.size() != r.bitArray.size()) { throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, - "modulo by zero"); - } - if (hasLong) { - Value v; - v.type = Value::Type::Long; - v.longValue = lInt % rInt; - return v; - } - return {Value::Type::Int, static_cast(lInt % rInt)}; - } - - if (bin->op == ">") { - if (hasFloat) - return makeBoolean(lNum > rNum); - return makeBoolean(lInt > rInt); - } - if (bin->op == "<") { - if (hasFloat) - return makeBoolean(lNum < rNum); - return makeBoolean(lInt < rInt); - } - if (bin->op == ">=") { - if (hasFloat) - return makeBoolean(lNum >= rNum); - return makeBoolean(lInt >= rInt); - } - if (bin->op == "<=") { - if (hasFloat) - return makeBoolean(lNum <= rNum); - return makeBoolean(lInt <= rInt); - } - if (bin->op == "==") { - if (hasFloat) - return makeBoolean(lNum == rNum); - return makeBoolean(lInt == rInt); - } - if (bin->op == "!=") { - if (hasFloat) - return makeBoolean(lNum != rNum); - return makeBoolean(lInt != rInt); - } - if (bin->op == "&&") { - bool lb = l.type == Value::Type::Float ? lNum != 0.0 : lInt != 0; - bool rb = r.type == Value::Type::Float ? rNum != 0.0 : rInt != 0; - return makeBoolean(lb && rb); - } - if (bin->op == "||") { - bool lb = l.type == Value::Type::Float ? lNum != 0.0 : lInt != 0; - bool rb = r.type == Value::Type::Float ? rNum != 0.0 : rInt != 0; - return makeBoolean(lb || rb); - } - if (bin->op == "&") { - if (l.type == Value::Type::Bit && r.type == Value::Type::Bit) - return {Value::Type::Bit, 0, 0.0, l.bitValue & r.bitValue}; - if (l.type == Value::Type::BitArray && r.type == Value::Type::BitArray) { - if (l.bitArray.size() != r.bitArray.size()) { - throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, - "bit arrays must be same length for '&'"); - } - Value v; - v.type = Value::Type::BitArray; - v.bitArray.resize(l.bitArray.size()); - for (size_t i = 0; i < l.bitArray.size(); ++i) - v.bitArray[i] = l.bitArray[i] & r.bitArray[i]; - return v; - } - if (l.type == Value::Type::BitArray && r.type == Value::Type::Bit) { - Value v; - v.type = Value::Type::BitArray; - v.bitArray.resize(l.bitArray.size()); - for (size_t i = 0; i < l.bitArray.size(); ++i) - v.bitArray[i] = l.bitArray[i] & r.bitValue; - return v; - } - if (l.type == Value::Type::Bit && r.type == Value::Type::BitArray) { - Value v; - v.type = Value::Type::BitArray; - v.bitArray.resize(r.bitArray.size()); - for (size_t i = 0; i < r.bitArray.size(); ++i) - v.bitArray[i] = l.bitValue & r.bitArray[i]; - return v; - } - throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, - "bitwise '&' requires bit or bit[] operands"); - } - if (bin->op == "|") { - if (l.type == Value::Type::Bit && r.type == Value::Type::Bit) - return {Value::Type::Bit, 0, 0.0, l.bitValue | r.bitValue}; - if (l.type == Value::Type::BitArray && r.type == Value::Type::BitArray) { - if (l.bitArray.size() != r.bitArray.size()) { - throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, - "bit arrays must be same length for '|'"); - } - Value v; - v.type = Value::Type::BitArray; - v.bitArray.resize(l.bitArray.size()); - for (size_t i = 0; i < l.bitArray.size(); ++i) - v.bitArray[i] = l.bitArray[i] | r.bitArray[i]; - return v; - } - if (l.type == Value::Type::BitArray && r.type == Value::Type::Bit) { - Value v; - v.type = Value::Type::BitArray; - v.bitArray.resize(l.bitArray.size()); - for (size_t i = 0; i < l.bitArray.size(); ++i) - v.bitArray[i] = l.bitArray[i] | r.bitValue; - return v; - } - if (l.type == Value::Type::Bit && r.type == Value::Type::BitArray) { - Value v; - v.type = Value::Type::BitArray; - v.bitArray.resize(r.bitArray.size()); - for (size_t i = 0; i < r.bitArray.size(); ++i) - v.bitArray[i] = l.bitValue | r.bitArray[i]; - return v; - } - throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, - "bitwise '|' requires bit or bit[] operands"); - } - if (bin->op == "^") { - if (l.type == Value::Type::Bit && r.type == Value::Type::Bit) - return {Value::Type::Bit, 0, 0.0, l.bitValue ^ r.bitValue}; - if (l.type == Value::Type::BitArray && r.type == Value::Type::BitArray) { - if (l.bitArray.size() != r.bitArray.size()) { - throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, - "bit arrays must be same length for '^'"); - } - Value v; - v.type = Value::Type::BitArray; - v.bitArray.resize(l.bitArray.size()); - for (size_t i = 0; i < l.bitArray.size(); ++i) - v.bitArray[i] = l.bitArray[i] ^ r.bitArray[i]; - return v; - } - if (l.type == Value::Type::BitArray && r.type == Value::Type::Bit) { - Value v; - v.type = Value::Type::BitArray; - v.bitArray.resize(l.bitArray.size()); - for (size_t i = 0; i < l.bitArray.size(); ++i) - v.bitArray[i] = l.bitArray[i] ^ r.bitValue; - return v; - } - if (l.type == Value::Type::Bit && r.type == Value::Type::BitArray) { - Value v; - v.type = Value::Type::BitArray; - v.bitArray.resize(r.bitArray.size()); - for (size_t i = 0; i < r.bitArray.size(); ++i) - v.bitArray[i] = l.bitValue ^ r.bitArray[i]; - return v; - } - throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, - "bitwise '^' requires bit or bit[] operands"); - } - } else if (auto unary = dynamic_cast(e)) { - Value r = eval(unary->right.get()); - if (unary->op == "-") { - if (r.type == Value::Type::Float) - return {Value::Type::Float, 0, -r.floatValue}; - if (r.type == Value::Type::Long) { - Value v; - v.type = Value::Type::Long; - v.longValue = -r.longValue; - return v; + "bit arrays must be same length for '|'"); } - return {Value::Type::Int, -r.intValue}; + Value v; + v.type = Value::Type::BitArray; + v.bitArray.resize(l.bitArray.size()); + for (size_t i = 0; i < l.bitArray.size(); ++i) + v.bitArray[i] = l.bitArray[i] | r.bitArray[i]; + return v; } - if (unary->op == "!") { - if (r.type == Value::Type::BitArray || r.type == Value::Type::BooleanArray) { - throw BlochError(ErrorCategory::Runtime, unary->line, unary->column, - "logical '!' unsupported for bit[] or boolean[]"); - } - bool rb = false; - if (r.type == Value::Type::Boolean) - rb = r.boolValue; - else if (r.type == Value::Type::Float) - rb = r.floatValue != 0.0; - else if (r.type == Value::Type::Long) - rb = r.longValue != 0; - else if (r.type == Value::Type::Bit) - rb = r.bitValue != 0; - else if (r.type == Value::Type::Int) - rb = r.intValue != 0; + if (l.type == Value::Type::BitArray && r.type == Value::Type::Bit) { Value v; - v.type = Value::Type::Boolean; - v.boolValue = !rb; + v.type = Value::Type::BitArray; + v.bitArray.resize(l.bitArray.size()); + for (size_t i = 0; i < l.bitArray.size(); ++i) + v.bitArray[i] = l.bitArray[i] | r.bitValue; return v; } - if (unary->op == "~") { - if (r.type == Value::Type::Bit) - return {Value::Type::Bit, 0, 0.0, r.bitValue ? 0 : 1}; - if (r.type == Value::Type::BitArray) { - Value v; - v.type = Value::Type::BitArray; - v.bitArray.resize(r.bitArray.size()); - for (size_t i = 0; i < r.bitArray.size(); ++i) - v.bitArray[i] = r.bitArray[i] ? 0 : 1; - return v; + if (l.type == Value::Type::Bit && r.type == Value::Type::BitArray) { + Value v; + v.type = Value::Type::BitArray; + v.bitArray.resize(r.bitArray.size()); + for (size_t i = 0; i < r.bitArray.size(); ++i) + v.bitArray[i] = l.bitValue | r.bitArray[i]; + return v; + } + throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, + "bitwise '|' requires bit or bit[] operands"); + } + if (bin->op == "^") { + if (l.type == Value::Type::Bit && r.type == Value::Type::Bit) + return {Value::Type::Bit, 0, 0.0, l.bitValue ^ r.bitValue}; + if (l.type == Value::Type::BitArray && r.type == Value::Type::BitArray) { + if (l.bitArray.size() != r.bitArray.size()) { + throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, + "bit arrays must be same length for '^'"); } + Value v; + v.type = Value::Type::BitArray; + v.bitArray.resize(l.bitArray.size()); + for (size_t i = 0; i < l.bitArray.size(); ++i) + v.bitArray[i] = l.bitArray[i] ^ r.bitArray[i]; + return v; + } + if (l.type == Value::Type::BitArray && r.type == Value::Type::Bit) { + Value v; + v.type = Value::Type::BitArray; + v.bitArray.resize(l.bitArray.size()); + for (size_t i = 0; i < l.bitArray.size(); ++i) + v.bitArray[i] = l.bitArray[i] ^ r.bitValue; + return v; + } + if (l.type == Value::Type::Bit && r.type == Value::Type::BitArray) { + Value v; + v.type = Value::Type::BitArray; + v.bitArray.resize(r.bitArray.size()); + for (size_t i = 0; i < r.bitArray.size(); ++i) + v.bitArray[i] = l.bitValue ^ r.bitArray[i]; + return v; + } + throw BlochError(ErrorCategory::Runtime, bin->line, bin->column, + "bitwise '^' requires bit or bit[] operands"); + } + } else if (auto unary = dynamic_cast(e)) { + Value r = eval(unary->right.get()); + if (unary->op == "-") { + if (r.type == Value::Type::Float) + return {Value::Type::Float, 0, -r.floatValue}; + if (r.type == Value::Type::Long) { + Value v; + v.type = Value::Type::Long; + v.longValue = -r.longValue; + return v; + } + return {Value::Type::Int, -r.intValue}; + } + if (unary->op == "!") { + if (r.type == Value::Type::BitArray || r.type == Value::Type::BooleanArray) { throw BlochError(ErrorCategory::Runtime, unary->line, unary->column, - "bitwise '~' requires bit or bit[] operand"); - } - return r; - } else if (auto post = dynamic_cast(e)) { - if (auto var = dynamic_cast(post->left.get())) { - Value current = lookup(var->name); - Value updated = current; - if (post->op == "++") { - if (current.type == Value::Type::Float) - updated.floatValue += 1.0; - else if (current.type == Value::Type::Long) - updated.longValue += 1; - else if (current.type == Value::Type::Int) - updated.intValue += 1; - } else if (post->op == "--") { - if (current.type == Value::Type::Float) - updated.floatValue -= 1.0; - else if (current.type == Value::Type::Long) - updated.longValue -= 1; - else if (current.type == Value::Type::Int) - updated.intValue -= 1; - } - assign(var->name, updated); - return current; - } - return {}; - } else if (auto callExpr = dynamic_cast(e)) { - if (auto var = dynamic_cast(callExpr->callee.get())) { - auto name = var->name; - auto builtin = builtInGates.find(name); - std::vector args; - for (auto& a : callExpr->arguments) args.push_back(eval(a.get())); - if (builtin != builtInGates.end()) { - // Map built-ins directly to simulator operations. - // TODO: In the noisy simulator this logic will have to remain the same - // so we will need the same basic quantum operations - if (name == "h") { - ensureQubitActive(args[0].qubit, callExpr->line, callExpr->column); - m_sim.h(args[0].qubit); - } else if (name == "x") { - ensureQubitActive(args[0].qubit, callExpr->line, callExpr->column); - m_sim.x(args[0].qubit); - } else if (name == "y") { - ensureQubitActive(args[0].qubit, callExpr->line, callExpr->column); - m_sim.y(args[0].qubit); - } else if (name == "z") { - ensureQubitActive(args[0].qubit, callExpr->line, callExpr->column); - m_sim.z(args[0].qubit); - } else if (name == "rx") { - ensureQubitActive(args[0].qubit, callExpr->line, callExpr->column); - m_sim.rx(args[0].qubit, args[1].floatValue); - } else if (name == "ry") { - ensureQubitActive(args[0].qubit, callExpr->line, callExpr->column); - m_sim.ry(args[0].qubit, args[1].floatValue); - } else if (name == "rz") { - ensureQubitActive(args[0].qubit, callExpr->line, callExpr->column); - m_sim.rz(args[0].qubit, args[1].floatValue); - } else if (name == "cx") { - ensureQubitActive(args[0].qubit, callExpr->line, callExpr->column); - ensureQubitActive(args[1].qubit, callExpr->line, callExpr->column); - m_sim.cx(args[0].qubit, args[1].qubit); - } - return {}; // void - } - auto fit = m_functions.find(name); - if (fit != m_functions.end()) { - auto res = call(fit->second, args); - if (fit->second->hasQuantumAnnotation && res.type == Value::Type::Bit) { - m_measurements[e].push_back(res.bitValue); + "logical '!' unsupported for bit[] or boolean[]"); + } + bool rb = false; + if (r.type == Value::Type::Boolean) + rb = r.boolValue; + else if (r.type == Value::Type::Float) + rb = r.floatValue != 0.0; + else if (r.type == Value::Type::Long) + rb = r.longValue != 0; + else if (r.type == Value::Type::Bit) + rb = r.bitValue != 0; + else if (r.type == Value::Type::Int) + rb = r.intValue != 0; + Value v; + v.type = Value::Type::Boolean; + v.boolValue = !rb; + return v; + } + if (unary->op == "~") { + if (r.type == Value::Type::Bit) + return {Value::Type::Bit, 0, 0.0, r.bitValue ? 0 : 1}; + if (r.type == Value::Type::BitArray) { + Value v; + v.type = Value::Type::BitArray; + v.bitArray.resize(r.bitArray.size()); + for (size_t i = 0; i < r.bitArray.size(); ++i) + v.bitArray[i] = r.bitArray[i] ? 0 : 1; + return v; + } + throw BlochError(ErrorCategory::Runtime, unary->line, unary->column, + "bitwise '~' requires bit or bit[] operand"); + } + return r; + } else if (auto post = dynamic_cast(e)) { + if (auto var = dynamic_cast(post->left.get())) { + Value current = lookup(var->name); + Value updated = current; + if (post->op == "++") { + if (current.type == Value::Type::Float) + updated.floatValue += 1.0; + else if (current.type == Value::Type::Long) + updated.longValue += 1; + else if (current.type == Value::Type::Int) + updated.intValue += 1; + } else if (post->op == "--") { + if (current.type == Value::Type::Float) + updated.floatValue -= 1.0; + else if (current.type == Value::Type::Long) + updated.longValue -= 1; + else if (current.type == Value::Type::Int) + updated.intValue -= 1; + } + assign(var->name, updated); + return current; + } + return {}; + } else if (auto callExpr = dynamic_cast(e)) { + if (auto var = dynamic_cast(callExpr->callee.get())) { + auto name = var->name; + auto builtin = builtInGates.find(name); + std::vector args; + for (auto& a : callExpr->arguments) + args.push_back(eval(a.get())); + if (builtin != builtInGates.end()) { + // Map built-ins directly to simulator operations. + // TODO: In the noisy simulator this logic will have to remain the same + // so we will need the same basic quantum operations + if (name == "h") { + ensureQubitActive(args[0].qubit, callExpr->line, callExpr->column); + m_sim.h(args[0].qubit); + } else if (name == "x") { + ensureQubitActive(args[0].qubit, callExpr->line, callExpr->column); + m_sim.x(args[0].qubit); + } else if (name == "y") { + ensureQubitActive(args[0].qubit, callExpr->line, callExpr->column); + m_sim.y(args[0].qubit); + } else if (name == "z") { + ensureQubitActive(args[0].qubit, callExpr->line, callExpr->column); + m_sim.z(args[0].qubit); + } else if (name == "rx") { + ensureQubitActive(args[0].qubit, callExpr->line, callExpr->column); + m_sim.rx(args[0].qubit, args[1].floatValue); + } else if (name == "ry") { + ensureQubitActive(args[0].qubit, callExpr->line, callExpr->column); + m_sim.ry(args[0].qubit, args[1].floatValue); + } else if (name == "rz") { + ensureQubitActive(args[0].qubit, callExpr->line, callExpr->column); + m_sim.rz(args[0].qubit, args[1].floatValue); + } else if (name == "cx") { + ensureQubitActive(args[0].qubit, callExpr->line, callExpr->column); + ensureQubitActive(args[1].qubit, callExpr->line, callExpr->column); + m_sim.cx(args[0].qubit, args[1].qubit); + } + return {}; // void + } + auto fit = m_functions.find(name); + if (fit != m_functions.end()) { + auto res = call(fit->second, args); + if (fit->second->hasQuantumAnnotation && res.type == Value::Type::Bit) { + m_measurements[e].push_back(res.bitValue); + } + return res; + } + RuntimeMethod* method = nullptr; + RuntimeClass* staticCls = m_currentClassCtx; + if (staticCls) + method = findMethod(staticCls, name, &args); + if (method) { + std::shared_ptr receiver; + if (!method->isStatic) { + receiver = currentThisObject(); + if (!receiver) { + throw BlochError( + ErrorCategory::Runtime, callExpr->line, callExpr->column, + "instance method '" + name + "' requires an object receiver"); } - return res; } - RuntimeMethod* method = nullptr; - RuntimeClass* staticCls = m_currentClassCtx; + return callMethod(method, staticCls, receiver, args); + } + } else if (auto member = dynamic_cast(callExpr->callee.get())) { + std::vector args; + for (auto& a : callExpr->arguments) + args.push_back(eval(a.get())); + Value target = eval(member->object.get()); + if (isNullReference(target)) { + throw BlochError(ErrorCategory::Runtime, member->line, member->column, + "null reference"); + } + RuntimeMethod* method = nullptr; + RuntimeClass* staticCls = nullptr; + std::shared_ptr receiver; + bool viaSuper = dynamic_cast(member->object.get()) != nullptr; + if (target.type == Value::Type::Object && target.objectValue) { + receiver = target.objectValue; + staticCls = !target.className.empty() ? findClass(target.className) : nullptr; + if (!staticCls) + staticCls = receiver->cls; + method = findMethod(staticCls, member->member, &args); + if (method && method->isVirtual && receiver->cls) { + auto it = receiver->cls->vtable.find(method->signature); + if (it != receiver->cls->vtable.end()) + method = it->second; + } + if (viaSuper && staticCls && staticCls->base) { + method = findMethod(staticCls->base, member->member, &args); + staticCls = staticCls->base; + } + } else if (target.type == Value::Type::ClassRef && target.classRef) { + staticCls = target.classRef; + method = findMethod(staticCls, member->member, &args); + } else if (target.type == Value::Type::ClassRef && !target.classRef && + !target.className.empty()) { + // Static call on a generic template (e.g., List.of(x)) — attempt to + // instantiate using argument types. + std::vector inferred; + if (!args.empty()) + inferred.push_back(typeInfoFromValue(args.front())); + staticCls = instantiateGeneric(target.className, inferred); if (staticCls) - method = findMethod(staticCls, name, &args); - if (method) { - std::shared_ptr receiver; - if (!method->isStatic) { - receiver = currentThisObject(); - if (!receiver) { - throw BlochError( - ErrorCategory::Runtime, callExpr->line, callExpr->column, - "instance method '" + name + "' requires an object receiver"); - } - } - return callMethod(method, staticCls, receiver, args); - } - } else if (auto member = - dynamic_cast(callExpr->callee.get())) { - std::vector args; - for (auto& a : callExpr->arguments) args.push_back(eval(a.get())); - Value target = eval(member->object.get()); - if (isNullReference(target)) { - throw BlochError(ErrorCategory::Runtime, member->line, member->column, - "null reference"); - } - RuntimeMethod* method = nullptr; - RuntimeClass* staticCls = nullptr; - std::shared_ptr receiver; - bool viaSuper = dynamic_cast(member->object.get()) != nullptr; - if (target.type == Value::Type::Object && target.objectValue) { - receiver = target.objectValue; - staticCls = !target.className.empty() ? findClass(target.className) : nullptr; - if (!staticCls) - staticCls = receiver->cls; - method = findMethod(staticCls, member->member, &args); - if (method && method->isVirtual && receiver->cls) { - auto it = receiver->cls->vtable.find(method->signature); - if (it != receiver->cls->vtable.end()) - method = it->second; - } - if (viaSuper && staticCls && staticCls->base) { - method = findMethod(staticCls->base, member->member, &args); - staticCls = staticCls->base; - } - } else if (target.type == Value::Type::ClassRef && target.classRef) { - staticCls = target.classRef; method = findMethod(staticCls, member->member, &args); - } else if (target.type == Value::Type::ClassRef && !target.classRef && - !target.className.empty()) { - // Static call on a generic template (e.g., List.of(x)) — attempt to - // instantiate using argument types. - std::vector inferred; - if (!args.empty()) - inferred.push_back(typeInfoFromValue(args.front())); - staticCls = instantiateGeneric(target.className, inferred); - if (staticCls) - method = findMethod(staticCls, member->member, &args); - } - if (method) { - return callMethod(method, staticCls, receiver, args); - } } - } else if (auto idx = dynamic_cast(e)) { - Value q = eval(idx->qubit.get()); - ensureQubitActive(q.qubit, idx->line, idx->column); - int bit = m_sim.measure(q.qubit); - markMeasured(q.qubit); - if (q.qubit >= 0 && q.qubit < static_cast(m_lastMeasurement.size())) - m_lastMeasurement[q.qubit] = bit; - m_measurements[e].push_back(bit); - return {Value::Type::Bit, 0, 0.0, bit}; - } else if (auto indexExpr = dynamic_cast(e)) { - Value coll = eval(indexExpr->collection.get()); - Value idxv = eval(indexExpr->index.get()); - int idxi = 0; - if (idxv.type == Value::Type::Int) - idxi = idxv.intValue; - else if (idxv.type == Value::Type::Long) - idxi = static_cast(idxv.longValue); - else if (idxv.type == Value::Type::Bit) - idxi = idxv.bitValue; - else if (idxv.type == Value::Type::Float) - idxi = static_cast(idxv.floatValue); - else - throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, - "index must be numeric"); - switch (coll.type) { - case Value::Type::BitArray: - if (idxi < 0 || idxi >= static_cast(coll.bitArray.size())) - throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, - "index " + std::to_string(idxi) + - " out of bounds for length " + - std::to_string(coll.bitArray.size())); - return {Value::Type::Bit, 0, 0.0, coll.bitArray[idxi]}; - case Value::Type::IntArray: - if (idxi < 0 || idxi >= static_cast(coll.intArray.size())) - throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, - "index " + std::to_string(idxi) + - " out of bounds for length " + - std::to_string(coll.intArray.size())); - return {Value::Type::Int, coll.intArray[idxi]}; - case Value::Type::LongArray: - if (idxi < 0 || idxi >= static_cast(coll.longArray.size())) - throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, - "index " + std::to_string(idxi) + - " out of bounds for length " + - std::to_string(coll.longArray.size())); - { - Value v; - v.type = Value::Type::Long; - v.longValue = coll.longArray[idxi]; - return v; - } - case Value::Type::FloatArray: - if (idxi < 0 || idxi >= static_cast(coll.floatArray.size())) - throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, - "index " + std::to_string(idxi) + - " out of bounds for length " + - std::to_string(coll.floatArray.size())); - return {Value::Type::Float, 0, coll.floatArray[idxi]}; - case Value::Type::BooleanArray: { - if (idxi < 0 || idxi >= static_cast(coll.boolArray.size())) - throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, - "index " + std::to_string(idxi) + - " out of bounds for length " + - std::to_string(coll.boolArray.size())); + if (method) { + return callMethod(method, staticCls, receiver, args); + } + } + } else if (auto idx = dynamic_cast(e)) { + Value q = eval(idx->qubit.get()); + ensureQubitActive(q.qubit, idx->line, idx->column); + int bit = m_sim.measure(q.qubit); + markMeasured(q.qubit); + if (q.qubit >= 0 && q.qubit < static_cast(m_lastMeasurement.size())) + m_lastMeasurement[q.qubit] = bit; + m_measurements[e].push_back(bit); + return {Value::Type::Bit, 0, 0.0, bit}; + } else if (auto indexExpr = dynamic_cast(e)) { + Value coll = eval(indexExpr->collection.get()); + Value idxv = eval(indexExpr->index.get()); + int idxi = 0; + if (idxv.type == Value::Type::Int) + idxi = idxv.intValue; + else if (idxv.type == Value::Type::Long) + idxi = static_cast(idxv.longValue); + else if (idxv.type == Value::Type::Bit) + idxi = idxv.bitValue; + else if (idxv.type == Value::Type::Float) + idxi = static_cast(idxv.floatValue); + else + throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, + "index must be numeric"); + switch (coll.type) { + case Value::Type::BitArray: + if (idxi < 0 || idxi >= static_cast(coll.bitArray.size())) + throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, + "index " + std::to_string(idxi) + + " out of bounds for length " + + std::to_string(coll.bitArray.size())); + return {Value::Type::Bit, 0, 0.0, coll.bitArray[idxi]}; + case Value::Type::IntArray: + if (idxi < 0 || idxi >= static_cast(coll.intArray.size())) + throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, + "index " + std::to_string(idxi) + + " out of bounds for length " + + std::to_string(coll.intArray.size())); + return {Value::Type::Int, coll.intArray[idxi]}; + case Value::Type::LongArray: + if (idxi < 0 || idxi >= static_cast(coll.longArray.size())) + throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, + "index " + std::to_string(idxi) + + " out of bounds for length " + + std::to_string(coll.longArray.size())); + { Value v; - v.type = Value::Type::Boolean; - v.boolValue = coll.boolArray[idxi]; + v.type = Value::Type::Long; + v.longValue = coll.longArray[idxi]; return v; } - case Value::Type::StringArray: - if (idxi < 0 || idxi >= static_cast(coll.stringArray.size())) - throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, - "index " + std::to_string(idxi) + - " out of bounds for length " + - std::to_string(coll.stringArray.size())); - return {Value::Type::String, 0, 0.0, 0, coll.stringArray[idxi]}; - case Value::Type::CharArray: - if (idxi < 0 || idxi >= static_cast(coll.charArray.size())) - throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, - "index " + std::to_string(idxi) + - " out of bounds for length " + - std::to_string(coll.charArray.size())); - { - Value v; - v.type = Value::Type::Char; - v.charValue = coll.charArray[idxi]; - return v; - } - case Value::Type::QubitArray: { - if (idxi < 0 || idxi >= static_cast(coll.qubitArray.size())) - throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, - "index " + std::to_string(idxi) + - " out of bounds for length " + - std::to_string(coll.qubitArray.size())); + case Value::Type::FloatArray: + if (idxi < 0 || idxi >= static_cast(coll.floatArray.size())) + throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, + "index " + std::to_string(idxi) + + " out of bounds for length " + + std::to_string(coll.floatArray.size())); + return {Value::Type::Float, 0, coll.floatArray[idxi]}; + case Value::Type::BooleanArray: { + if (idxi < 0 || idxi >= static_cast(coll.boolArray.size())) + throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, + "index " + std::to_string(idxi) + + " out of bounds for length " + + std::to_string(coll.boolArray.size())); + Value v; + v.type = Value::Type::Boolean; + v.boolValue = coll.boolArray[idxi]; + return v; + } + case Value::Type::StringArray: + if (idxi < 0 || idxi >= static_cast(coll.stringArray.size())) + throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, + "index " + std::to_string(idxi) + + " out of bounds for length " + + std::to_string(coll.stringArray.size())); + return {Value::Type::String, 0, 0.0, 0, coll.stringArray[idxi]}; + case Value::Type::CharArray: + if (idxi < 0 || idxi >= static_cast(coll.charArray.size())) + throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, + "index " + std::to_string(idxi) + + " out of bounds for length " + + std::to_string(coll.charArray.size())); + { Value v; - v.type = Value::Type::Qubit; - v.qubit = coll.qubitArray[idxi]; + v.type = Value::Type::Char; + v.charValue = coll.charArray[idxi]; return v; } - default: + case Value::Type::QubitArray: { + if (idxi < 0 || idxi >= static_cast(coll.qubitArray.size())) throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, - "indexing requires an array value"); - } - } else if (auto assignExpr = dynamic_cast(e)) { - Value v = eval(assignExpr->value.get()); - assign(assignExpr->name, v); - return v; - } else if (auto memAssign = dynamic_cast(e)) { - Value obj = eval(memAssign->object.get()); - if (isNullReference(obj)) { - throw BlochError(ErrorCategory::Runtime, memAssign->line, memAssign->column, - "null reference"); + "index " + std::to_string(idxi) + + " out of bounds for length " + + std::to_string(coll.qubitArray.size())); + Value v; + v.type = Value::Type::Qubit; + v.qubit = coll.qubitArray[idxi]; + return v; } - Value rhs = eval(memAssign->value.get()); - if (obj.type == Value::Type::Object && obj.objectValue) { - RuntimeField* instField = + default: + throw BlochError(ErrorCategory::Runtime, indexExpr->line, indexExpr->column, + "indexing requires an array value"); + } + } else if (auto assignExpr = dynamic_cast(e)) { + Value v = eval(assignExpr->value.get()); + assign(assignExpr->name, v); + return v; + } else if (auto memAssign = dynamic_cast(e)) { + Value obj = eval(memAssign->object.get()); + if (isNullReference(obj)) { + throw BlochError(ErrorCategory::Runtime, memAssign->line, memAssign->column, + "null reference"); + } + Value rhs = eval(memAssign->value.get()); + if (obj.type == Value::Type::Object && obj.objectValue) { + RuntimeField* instField = + obj.objectValue->cls ? findInstanceField(obj.objectValue->cls, memAssign->member) + : nullptr; + if (instField) { + if (instField->offset < obj.objectValue->fields.size()) + obj.objectValue->fields[instField->offset] = rhs; + } else { + auto [staticField, owner] = obj.objectValue->cls - ? findInstanceField(obj.objectValue->cls, memAssign->member) - : nullptr; - if (instField) { - if (instField->offset < obj.objectValue->fields.size()) - obj.objectValue->fields[instField->offset] = rhs; - } else { - auto [staticField, owner] = - obj.objectValue->cls - ? findStaticFieldWithOwner(obj.objectValue->cls, memAssign->member) - : std::pair{nullptr, nullptr}; - if (staticField && owner && staticField->offset < owner->staticStorage.size()) - owner->staticStorage[staticField->offset] = rhs; - } - } else if (obj.type == Value::Type::ClassRef && obj.classRef) { - auto [field, owner] = findStaticFieldWithOwner(obj.classRef, memAssign->member); - if (field && owner && field->offset < owner->staticStorage.size()) - owner->staticStorage[field->offset] = rhs; - } - return rhs; - } else if (auto aassign = dynamic_cast(e)) { - // Only support assigning into variable arrays for 1.0.0 - auto* var = dynamic_cast(aassign->collection.get()); - if (!var) - throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, - "assignment target must be a variable"); - Value arr = lookup(var->name); - Value idxv = eval(aassign->index.get()); - int i = 0; - if (idxv.type == Value::Type::Int) - i = idxv.intValue; - else if (idxv.type == Value::Type::Long) - i = static_cast(idxv.longValue); - else if (idxv.type == Value::Type::Bit) - i = idxv.bitValue; - else if (idxv.type == Value::Type::Float) - i = static_cast(idxv.floatValue); - else - throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, - "index must be numeric"); - Value rhs = eval(aassign->value.get()); - switch (arr.type) { - case Value::Type::IntArray: - if (i < 0 || i >= static_cast(arr.intArray.size())) - throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, - "index " + std::to_string(i) + - " out of bounds for length " + - std::to_string(arr.intArray.size())); - if (rhs.type == Value::Type::Int) - arr.intArray[i] = rhs.intValue; - else if (rhs.type == Value::Type::Long) - arr.intArray[i] = static_cast(rhs.longValue); - else if (rhs.type == Value::Type::Bit) - arr.intArray[i] = rhs.bitValue; - else if (rhs.type == Value::Type::Float) - arr.intArray[i] = static_cast(rhs.floatValue); - else - throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, - "type mismatch for int[] assignment"); - break; - case Value::Type::LongArray: - if (i < 0 || i >= static_cast(arr.longArray.size())) - throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, - "index " + std::to_string(i) + - " out of bounds for length " + - std::to_string(arr.longArray.size())); - if (rhs.type == Value::Type::Long) - arr.longArray[i] = rhs.longValue; - else if (rhs.type == Value::Type::Int) - arr.longArray[i] = rhs.intValue; - else if (rhs.type == Value::Type::Bit) - arr.longArray[i] = rhs.bitValue; - else if (rhs.type == Value::Type::Float) - arr.longArray[i] = static_cast(rhs.floatValue); - else - throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, - "type mismatch for long[] assignment"); - break; - case Value::Type::FloatArray: - if (i < 0 || i >= static_cast(arr.floatArray.size())) - throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, - "index " + std::to_string(i) + - " out of bounds for length " + - std::to_string(arr.floatArray.size())); - if (rhs.type == Value::Type::Float) - arr.floatArray[i] = rhs.floatValue; - else if (rhs.type == Value::Type::Int) - arr.floatArray[i] = static_cast(rhs.intValue); - else if (rhs.type == Value::Type::Long) - arr.floatArray[i] = static_cast(rhs.longValue); - else if (rhs.type == Value::Type::Bit) - arr.floatArray[i] = static_cast(rhs.bitValue); - else - throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, - "type mismatch for float[] assignment"); - break; - case Value::Type::BitArray: - if (i < 0 || i >= static_cast(arr.bitArray.size())) - throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, - "index " + std::to_string(i) + - " out of bounds for length " + - std::to_string(arr.bitArray.size())); - if (rhs.type == Value::Type::Bit) - arr.bitArray[i] = rhs.bitValue ? 1 : 0; - else if (rhs.type == Value::Type::Int) - arr.bitArray[i] = (rhs.intValue != 0) ? 1 : 0; - else - throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, - "type mismatch for bit[] assignment"); - break; - case Value::Type::BooleanArray: - if (i < 0 || i >= static_cast(arr.boolArray.size())) - throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, - "index " + std::to_string(i) + - " out of bounds for length " + - std::to_string(arr.boolArray.size())); - if (rhs.type == Value::Type::Boolean) - arr.boolArray[i] = rhs.boolValue; - else if (rhs.type == Value::Type::Bit) - arr.boolArray[i] = rhs.bitValue != 0; - else - throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, - "type mismatch for boolean[] assignment"); - break; - case Value::Type::StringArray: - if (i < 0 || i >= static_cast(arr.stringArray.size())) - throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, - "index " + std::to_string(i) + - " out of bounds for length " + - std::to_string(arr.stringArray.size())); - if (rhs.type == Value::Type::String) - arr.stringArray[i] = rhs.stringValue; - else - throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, - "type mismatch for string[] assignment"); - break; - case Value::Type::CharArray: - if (i < 0 || i >= static_cast(arr.charArray.size())) - throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, - "index " + std::to_string(i) + - " out of bounds for length " + - std::to_string(arr.charArray.size())); - if (rhs.type == Value::Type::Char) - arr.charArray[i] = rhs.charValue; - else - throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, - "type mismatch for char[] assignment"); - break; - default: - throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, - "assignment into this array type is unsupported"); + ? findStaticFieldWithOwner(obj.objectValue->cls, memAssign->member) + : std::pair{nullptr, nullptr}; + if (staticField && owner && staticField->offset < owner->staticStorage.size()) + owner->staticStorage[staticField->offset] = rhs; } - assign(var->name, arr); - return arr; - } - return {}; - } - - int RuntimeEvaluator::allocateTrackedQubit(const std::string& name) { - int idx = -1; - if (!m_freeQubitIndices.empty()) { - idx = m_freeQubitIndices.back(); - m_freeQubitIndices.pop_back(); - m_sim.reset(idx); - unmarkMeasured(idx); - } else { - idx = m_sim.allocateQubit(); - m_qubits.push_back({name, false}); + } else if (obj.type == Value::Type::ClassRef && obj.classRef) { + auto [field, owner] = findStaticFieldWithOwner(obj.classRef, memAssign->member); + if (field && owner && field->offset < owner->staticStorage.size()) + owner->staticStorage[field->offset] = rhs; + } + return rhs; + } else if (auto aassign = dynamic_cast(e)) { + // Only support assigning into variable arrays for 1.0.0 + auto* var = dynamic_cast(aassign->collection.get()); + if (!var) + throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, + "assignment target must be a variable"); + Value arr = lookup(var->name); + Value idxv = eval(aassign->index.get()); + int i = 0; + if (idxv.type == Value::Type::Int) + i = idxv.intValue; + else if (idxv.type == Value::Type::Long) + i = static_cast(idxv.longValue); + else if (idxv.type == Value::Type::Bit) + i = idxv.bitValue; + else if (idxv.type == Value::Type::Float) + i = static_cast(idxv.floatValue); + else + throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, + "index must be numeric"); + Value rhs = eval(aassign->value.get()); + switch (arr.type) { + case Value::Type::IntArray: + if (i < 0 || i >= static_cast(arr.intArray.size())) + throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, + "index " + std::to_string(i) + " out of bounds for length " + + std::to_string(arr.intArray.size())); + if (rhs.type == Value::Type::Int) + arr.intArray[i] = rhs.intValue; + else if (rhs.type == Value::Type::Long) + arr.intArray[i] = static_cast(rhs.longValue); + else if (rhs.type == Value::Type::Bit) + arr.intArray[i] = rhs.bitValue; + else if (rhs.type == Value::Type::Float) + arr.intArray[i] = static_cast(rhs.floatValue); + else + throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, + "type mismatch for int[] assignment"); + break; + case Value::Type::LongArray: + if (i < 0 || i >= static_cast(arr.longArray.size())) + throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, + "index " + std::to_string(i) + " out of bounds for length " + + std::to_string(arr.longArray.size())); + if (rhs.type == Value::Type::Long) + arr.longArray[i] = rhs.longValue; + else if (rhs.type == Value::Type::Int) + arr.longArray[i] = rhs.intValue; + else if (rhs.type == Value::Type::Bit) + arr.longArray[i] = rhs.bitValue; + else if (rhs.type == Value::Type::Float) + arr.longArray[i] = static_cast(rhs.floatValue); + else + throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, + "type mismatch for long[] assignment"); + break; + case Value::Type::FloatArray: + if (i < 0 || i >= static_cast(arr.floatArray.size())) + throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, + "index " + std::to_string(i) + " out of bounds for length " + + std::to_string(arr.floatArray.size())); + if (rhs.type == Value::Type::Float) + arr.floatArray[i] = rhs.floatValue; + else if (rhs.type == Value::Type::Int) + arr.floatArray[i] = static_cast(rhs.intValue); + else if (rhs.type == Value::Type::Long) + arr.floatArray[i] = static_cast(rhs.longValue); + else if (rhs.type == Value::Type::Bit) + arr.floatArray[i] = static_cast(rhs.bitValue); + else + throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, + "type mismatch for float[] assignment"); + break; + case Value::Type::BitArray: + if (i < 0 || i >= static_cast(arr.bitArray.size())) + throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, + "index " + std::to_string(i) + " out of bounds for length " + + std::to_string(arr.bitArray.size())); + if (rhs.type == Value::Type::Bit) + arr.bitArray[i] = rhs.bitValue ? 1 : 0; + else if (rhs.type == Value::Type::Int) + arr.bitArray[i] = (rhs.intValue != 0) ? 1 : 0; + else + throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, + "type mismatch for bit[] assignment"); + break; + case Value::Type::BooleanArray: + if (i < 0 || i >= static_cast(arr.boolArray.size())) + throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, + "index " + std::to_string(i) + " out of bounds for length " + + std::to_string(arr.boolArray.size())); + if (rhs.type == Value::Type::Boolean) + arr.boolArray[i] = rhs.boolValue; + else if (rhs.type == Value::Type::Bit) + arr.boolArray[i] = rhs.bitValue != 0; + else + throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, + "type mismatch for boolean[] assignment"); + break; + case Value::Type::StringArray: + if (i < 0 || i >= static_cast(arr.stringArray.size())) + throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, + "index " + std::to_string(i) + " out of bounds for length " + + std::to_string(arr.stringArray.size())); + if (rhs.type == Value::Type::String) + arr.stringArray[i] = rhs.stringValue; + else + throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, + "type mismatch for string[] assignment"); + break; + case Value::Type::CharArray: + if (i < 0 || i >= static_cast(arr.charArray.size())) + throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, + "index " + std::to_string(i) + " out of bounds for length " + + std::to_string(arr.charArray.size())); + if (rhs.type == Value::Type::Char) + arr.charArray[i] = rhs.charValue; + else + throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, + "type mismatch for char[] assignment"); + break; + default: + throw BlochError(ErrorCategory::Runtime, aassign->line, aassign->column, + "assignment into this array type is unsupported"); } - if (idx >= static_cast(m_qubits.size())) - m_qubits.resize(idx + 1); - m_qubits[idx].name = name; - m_qubits[idx].measured = false; - if (idx >= static_cast(m_lastMeasurement.size())) - m_lastMeasurement.resize(idx + 1, -1); - return idx; - } - - void RuntimeEvaluator::markMeasured(int index) { - if (index >= 0 && index < static_cast(m_qubits.size())) - m_qubits[index].measured = true; + assign(var->name, arr); + return arr; } - - void RuntimeEvaluator::releaseQubit(int index) { - if (index < 0 || index >= static_cast(m_qubits.size())) - return; - unmarkMeasured(index); - m_qubits[index].name.clear(); - m_freeQubitIndices.push_back(index); + return {}; +} + +int RuntimeEvaluator::allocateTrackedQubit(const std::string& name) { + int idx = -1; + if (!m_freeQubitIndices.empty()) { + idx = m_freeQubitIndices.back(); + m_freeQubitIndices.pop_back(); + m_sim.reset(idx); + unmarkMeasured(idx); + } else { + idx = m_sim.allocateQubit(); + m_qubits.push_back({name, false}); } - - void RuntimeEvaluator::ensureQubitExists(int index, int line, int column) { - if (index < 0 || index >= static_cast(m_qubits.size())) - throw BlochError(ErrorCategory::Runtime, line, column, "invalid qubit reference"); + if (idx >= static_cast(m_qubits.size())) + m_qubits.resize(idx + 1); + m_qubits[idx].name = name; + m_qubits[idx].measured = false; + if (idx >= static_cast(m_lastMeasurement.size())) + m_lastMeasurement.resize(idx + 1, -1); + return idx; +} + +void RuntimeEvaluator::markMeasured(int index) { + if (index >= 0 && index < static_cast(m_qubits.size())) + m_qubits[index].measured = true; +} + +void RuntimeEvaluator::releaseQubit(int index) { + if (index < 0 || index >= static_cast(m_qubits.size())) + return; + unmarkMeasured(index); + m_qubits[index].name.clear(); + m_freeQubitIndices.push_back(index); +} + +void RuntimeEvaluator::ensureQubitExists(int index, int line, int column) { + if (index < 0 || index >= static_cast(m_qubits.size())) + throw BlochError(ErrorCategory::Runtime, line, column, "invalid qubit reference"); +} + +void RuntimeEvaluator::ensureQubitActive(int index, int line, int column) { + ensureQubitExists(index, line, column); + if (m_qubits[index].measured) { + std::string label = m_qubits[index].name.empty() + ? std::string("q[") + std::to_string(index) + "]" + : m_qubits[index].name; + throw BlochError(ErrorCategory::Runtime, line, column, + "qubit " + label + " has already been measured"); } - - void RuntimeEvaluator::ensureQubitActive(int index, int line, int column) { - ensureQubitExists(index, line, column); - if (m_qubits[index].measured) { - std::string label = m_qubits[index].name.empty() - ? std::string("q[") + std::to_string(index) + "]" - : m_qubits[index].name; - throw BlochError(ErrorCategory::Runtime, line, column, - "qubit " + label + " has already been measured"); +} + +void RuntimeEvaluator::unmarkMeasured(int index) { + if (index >= 0 && index < static_cast(m_qubits.size())) + m_qubits[index].measured = false; + if (index >= 0 && index < static_cast(m_lastMeasurement.size())) + m_lastMeasurement[index] = -1; +} + +void RuntimeEvaluator::warnUnmeasured() const { + for (const auto& q : m_qubits) { + if (q.name.empty()) + continue; + if (!q.measured) { + blochWarning( + 0, 0, + "Qubit " + q.name + " was left unmeasured. No classical value will be returned."); } } - - void RuntimeEvaluator::unmarkMeasured(int index) { - if (index >= 0 && index < static_cast(m_qubits.size())) - m_qubits[index].measured = false; - if (index >= 0 && index < static_cast(m_lastMeasurement.size())) - m_lastMeasurement[index] = -1; - } - - void RuntimeEvaluator::warnUnmeasured() const { - for (const auto& q : m_qubits) { - if (q.name.empty()) - continue; - if (!q.measured) { - blochWarning(0, 0, - "Qubit " + q.name + - " was left unmeasured. No classical value will be returned."); +} + +void RuntimeEvaluator::beginScope() { m_env.push_back({}); } + +void RuntimeEvaluator::endScope() { + if (m_env.empty()) + return; + for (auto& kv : m_env.back()) { + if (!kv.second.tracked) + continue; + const auto& name = kv.first; + const auto& entry = kv.second; + const auto& v = entry.value; + if (v.type == Value::Type::Qubit) { + int q = v.qubit; + std::string outcome = "?"; + if (q >= 0 && q < static_cast(m_lastMeasurement.size()) && + m_lastMeasurement[q] != -1) { + outcome = m_lastMeasurement[q] ? "1" : "0"; } - } - } - - void RuntimeEvaluator::beginScope() { m_env.push_back({}); } - - void RuntimeEvaluator::endScope() { - if (m_env.empty()) - return; - for (auto& kv : m_env.back()) { - if (!kv.second.tracked) - continue; - const auto& name = kv.first; - const auto& entry = kv.second; - const auto& v = entry.value; - if (v.type == Value::Type::Qubit) { - int q = v.qubit; - std::string outcome = "?"; - if (q >= 0 && q < static_cast(m_lastMeasurement.size()) && - m_lastMeasurement[q] != -1) { - outcome = m_lastMeasurement[q] ? "1" : "0"; - } - std::string key = std::string("qubit ") + name; - m_trackedCounts[key][outcome]++; - } else if (v.type == Value::Type::QubitArray) { - bool allMeasured = true; - std::string bits; - for (int q : v.qubitArray) { - if (!(q >= 0 && q < static_cast(m_lastMeasurement.size()) && - m_lastMeasurement[q] != -1)) { - allMeasured = false; - break; - } - } - std::string outcome; - if (!allMeasured) { - outcome = "?"; - } else { - for (int q : v.qubitArray) bits.push_back(m_lastMeasurement[q] ? '1' : '0'); - outcome = bits; + std::string key = std::string("qubit ") + name; + m_trackedCounts[key][outcome]++; + } else if (v.type == Value::Type::QubitArray) { + bool allMeasured = true; + std::string bits; + for (int q : v.qubitArray) { + if (!(q >= 0 && q < static_cast(m_lastMeasurement.size()) && + m_lastMeasurement[q] != -1)) { + allMeasured = false; + break; } - std::string key = std::string("qubit[] ") + name; - m_trackedCounts[key][outcome]++; } + std::string outcome; + if (!allMeasured) { + outcome = "?"; + } else { + for (int q : v.qubitArray) + bits.push_back(m_lastMeasurement[q] ? '1' : '0'); + outcome = bits; + } + std::string key = std::string("qubit[] ") + name; + m_trackedCounts[key][outcome]++; } - m_env.pop_back(); } + m_env.pop_back(); +} - void RuntimeEvaluator::flushEchoes() { - for (const auto& line : m_echoBuffer) { - std::cout << line << std::endl; - } - m_echoBuffer.clear(); +void RuntimeEvaluator::flushEchoes() { + for (const auto& line : m_echoBuffer) { + std::cout << line << std::endl; } - - size_t RuntimeEvaluator::heapObjectCount() { - std::lock_guard lock(m_heapMutex); - size_t count = 0; - for (const auto& w : m_heap) { - if (w.lock()) - ++count; - } - return count; + m_echoBuffer.clear(); +} + +size_t RuntimeEvaluator::heapObjectCount() { + std::lock_guard lock(m_heapMutex); + size_t count = 0; + for (const auto& w : m_heap) { + if (w.lock()) + ++count; } + return count; +} } // namespace bloch::runtime diff --git a/src/bloch/runtime/runtime_evaluator.hpp b/src/bloch/runtime/runtime_evaluator.hpp index c19f9f2..df85890 100644 --- a/src/bloch/runtime/runtime_evaluator.hpp +++ b/src/bloch/runtime/runtime_evaluator.hpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -33,324 +33,323 @@ namespace bloch::runtime { - class RuntimeEvaluator; - struct RuntimeClass; - struct Object; +class RuntimeEvaluator; +struct RuntimeClass; +struct Object; - using compiler::AnnotationNode; - using compiler::ArrayAssignmentExpression; - using compiler::ArrayLiteralExpression; - using compiler::ArrayType; - using compiler::AssignmentExpression; - using compiler::AssignmentStatement; - using compiler::BinaryExpression; - using compiler::BlockStatement; - using compiler::CallExpression; - using compiler::CastExpression; - using compiler::ConstructorDeclaration; - using compiler::DestroyStatement; - using compiler::DestructorDeclaration; - using compiler::EchoStatement; - using compiler::Expression; - using compiler::ExpressionStatement; - using compiler::FieldDeclaration; - using compiler::ForStatement; - using compiler::FunctionDeclaration; - using compiler::IfStatement; - using compiler::IndexExpression; - using compiler::LiteralExpression; - using compiler::MeasureExpression; - using compiler::MeasureStatement; - using compiler::MemberAccessExpression; - using compiler::MemberAssignmentExpression; - using compiler::MethodDeclaration; - using compiler::NamedType; - using compiler::NewExpression; - using compiler::NullLiteralExpression; - using compiler::Parameter; - using compiler::ParenthesizedExpression; - using compiler::PostfixExpression; - using compiler::PrimitiveType; - using compiler::Program; - using compiler::ResetStatement; - using compiler::ReturnStatement; - using compiler::Statement; - using compiler::SuperExpression; - using compiler::TernaryStatement; - using compiler::ThisExpression; - using compiler::Type; - using compiler::UnaryExpression; - using compiler::VariableDeclaration; - using compiler::VariableExpression; - using compiler::VoidType; - using compiler::WhileStatement; +using compiler::AnnotationNode; +using compiler::ArrayAssignmentExpression; +using compiler::ArrayLiteralExpression; +using compiler::ArrayType; +using compiler::AssignmentExpression; +using compiler::AssignmentStatement; +using compiler::BinaryExpression; +using compiler::BlockStatement; +using compiler::CallExpression; +using compiler::CastExpression; +using compiler::ConstructorDeclaration; +using compiler::DestroyStatement; +using compiler::DestructorDeclaration; +using compiler::EchoStatement; +using compiler::Expression; +using compiler::ExpressionStatement; +using compiler::FieldDeclaration; +using compiler::ForStatement; +using compiler::FunctionDeclaration; +using compiler::IfStatement; +using compiler::IndexExpression; +using compiler::LiteralExpression; +using compiler::MeasureExpression; +using compiler::MeasureStatement; +using compiler::MemberAccessExpression; +using compiler::MemberAssignmentExpression; +using compiler::MethodDeclaration; +using compiler::NamedType; +using compiler::NewExpression; +using compiler::NullLiteralExpression; +using compiler::Parameter; +using compiler::ParenthesizedExpression; +using compiler::PostfixExpression; +using compiler::PrimitiveType; +using compiler::Program; +using compiler::ResetStatement; +using compiler::ReturnStatement; +using compiler::Statement; +using compiler::SuperExpression; +using compiler::TernaryStatement; +using compiler::ThisExpression; +using compiler::Type; +using compiler::UnaryExpression; +using compiler::VariableDeclaration; +using compiler::VariableExpression; +using compiler::VoidType; +using compiler::WhileStatement; - // Runtime values carry both a discriminant and storage. Arrays are - // represented as std::vector<> of the appropriate primitive. - // REFACTOR: Replace this hand-rolled tagged union with std::variant + visitors - // to enforce exhaustive handling and shrink the switch-heavy evaluator. - struct Value { - enum class Type { - Int, - Long, - Float, - Bit, - Boolean, - String, - Char, - Qubit, - // Arrays - IntArray, - LongArray, - FloatArray, - BitArray, - BooleanArray, - StringArray, - CharArray, - QubitArray, - Object, - ObjectArray, - ClassRef, - Void - }; - Type type = Type::Void; - int intValue = 0; - std::int64_t longValue = 0; - double floatValue = 0.0; - int bitValue = 0; - bool boolValue = false; - std::string stringValue = ""; - char charValue = '\0'; - int qubit = -1; - std::vector intArray; - std::vector longArray; - std::vector floatArray; - std::vector bitArray; - std::vector boolArray; - std::vector stringArray; - std::vector charArray; - std::vector qubitArray; - std::shared_ptr objectValue; - std::vector> objectArray; - RuntimeClass* classRef = nullptr; - std::string className; - - Value() = default; - explicit Value(Type t) : type(t) {} - Value(Type t, int intVal, double floatVal = 0.0, int bitVal = 0, std::string strVal = "", - char charVal = '\0') - : type(t), - intValue(intVal), - floatValue(floatVal), - bitValue(bitVal), - stringValue(std::move(strVal)), - charValue(charVal) {} +// Runtime values carry both a discriminant and storage. Arrays are +// represented as std::vector<> of the appropriate primitive. +// REFACTOR: Replace this hand-rolled tagged union with std::variant + visitors +// to enforce exhaustive handling and shrink the switch-heavy evaluator. +struct Value { + enum class Type { + Int, + Long, + Float, + Bit, + Boolean, + String, + Char, + Qubit, + // Arrays + IntArray, + LongArray, + FloatArray, + BitArray, + BooleanArray, + StringArray, + CharArray, + QubitArray, + Object, + ObjectArray, + ClassRef, + Void }; + Type type = Type::Void; + int intValue = 0; + std::int64_t longValue = 0; + double floatValue = 0.0; + int bitValue = 0; + bool boolValue = false; + std::string stringValue = ""; + char charValue = '\0'; + int qubit = -1; + std::vector intArray; + std::vector longArray; + std::vector floatArray; + std::vector bitArray; + std::vector boolArray; + std::vector stringArray; + std::vector charArray; + std::vector qubitArray; + std::shared_ptr objectValue; + std::vector> objectArray; + RuntimeClass* classRef = nullptr; + std::string className; - struct RuntimeTypeInfo { - Value::Type kind = Value::Type::Void; - std::string className; - std::vector typeArgs; - }; + Value() = default; + explicit Value(Type t) : type(t) {} + Value(Type t, int intVal, double floatVal = 0.0, int bitVal = 0, std::string strVal = "", + char charVal = '\0') + : type(t), + intValue(intVal), + floatValue(floatVal), + bitValue(bitVal), + stringValue(std::move(strVal)), + charValue(charVal) {} +}; - struct RuntimeField { - std::string name; - RuntimeTypeInfo type; - bool isStatic = false; - bool isFinal = false; - bool isTracked = false; - Expression* initializer = nullptr; - bool hasInitializer = false; - int arraySize = -1; - int line = 0; - int column = 0; - size_t offset = 0; - }; +struct RuntimeTypeInfo { + Value::Type kind = Value::Type::Void; + std::string className; + std::vector typeArgs; +}; - struct RuntimeMethod; - struct RuntimeConstructor { - ConstructorDeclaration* decl = nullptr; - std::vector params; - bool isDefault = false; - }; +struct RuntimeField { + std::string name; + RuntimeTypeInfo type; + bool isStatic = false; + bool isFinal = false; + bool isTracked = false; + Expression* initializer = nullptr; + bool hasInitializer = false; + int arraySize = -1; + int line = 0; + int column = 0; + size_t offset = 0; +}; - struct RuntimeMethod { - MethodDeclaration* decl = nullptr; - bool isStatic = false; - bool isVirtual = false; - bool isOverride = false; - std::vector params; - std::string signature; - RuntimeClass* owner = nullptr; - }; +struct RuntimeMethod; +struct RuntimeConstructor { + ConstructorDeclaration* decl = nullptr; + std::vector params; + bool isDefault = false; +}; - struct RuntimeClass { - std::string name; - RuntimeClass* base = nullptr; - bool isStatic = false; - bool isAbstract = false; - bool hasDestructor = false; - bool hasTrackedFields = false; - DestructorDeclaration* destructorDecl = nullptr; - std::vector instanceFields; - std::vector staticFields; - std::vector staticStorage; - std::unordered_map instanceFieldIndex; - std::unordered_map staticFieldIndex; - std::unordered_map> methods; - std::unordered_map vtable; - std::vector constructors; - std::vector typeArgs; - std::vector typeParamNames; - }; +struct RuntimeMethod { + MethodDeclaration* decl = nullptr; + bool isStatic = false; + bool isVirtual = false; + bool isOverride = false; + std::vector params; + std::string signature; + RuntimeClass* owner = nullptr; +}; - struct Object { - RuntimeClass* cls = nullptr; - std::vector fields; - bool skipDestructor = false; - bool destroyed = false; - RuntimeEvaluator* owner = nullptr; - bool marked = false; - }; +struct RuntimeClass { + std::string name; + RuntimeClass* base = nullptr; + bool isStatic = false; + bool isAbstract = false; + bool hasDestructor = false; + bool hasTrackedFields = false; + DestructorDeclaration* destructorDecl = nullptr; + std::vector instanceFields; + std::vector staticFields; + std::vector staticStorage; + std::unordered_map instanceFieldIndex; + std::unordered_map staticFieldIndex; + std::unordered_map> methods; + std::unordered_map vtable; + std::vector constructors; + std::vector typeArgs; + std::vector typeParamNames; +}; - // Interpreter that walks the AST and simulates quantum bits via - // QasmSimulator. It also tracks @tracked variables and defers echo output - // until warnings have been printed. - // REFACTOR: Split this monolith into a Visitor-based expression evaluator + - // Strategy pluggable backend (statevector, hardware, mock) to isolate GC, - // qubit bookkeeping, and execution policy; current single class is ~god object. - class RuntimeEvaluator { - public: - explicit RuntimeEvaluator(bool collectQasmLog = true) : m_collectQasmLog(collectQasmLog) {} - ~RuntimeEvaluator(); - void execute(Program& program); - const std::unordered_map>& measurements() const { - return m_measurements; - } - std::string getQasm() const { return m_sim.getQasm(); } - size_t heapObjectCount(); +struct Object { + RuntimeClass* cls = nullptr; + std::vector fields; + bool skipDestructor = false; + bool destroyed = false; + RuntimeEvaluator* owner = nullptr; + bool marked = false; +}; - private: - QasmSimulator m_sim; - bool m_collectQasmLog = true; - std::unordered_map m_functions; - struct VarEntry { - Value value; - bool tracked = false; - bool initialized = false; - }; - std::vector> m_env; - Value m_returnValue; - bool m_hasReturn = false; - std::unordered_map> m_measurements; - std::unordered_map> m_trackedCounts; - bool m_echoEnabled = true; - bool m_warnOnExit = true; - bool m_executed = false; // single-use guard - // Class runtime metadata and heap tracking - std::unordered_map> m_classTable; - std::vector> m_heap; - RuntimeClass* m_currentClassCtx = nullptr; - bool m_inStaticContext = false; - bool m_inConstructor = false; - bool m_inDestructor = false; - std::atomic m_gcRequested{false}; - std::atomic m_stopGc{false}; - bool m_gcThreadStarted = false; - std::thread m_gcThread; - std::condition_variable m_gcCv; - std::mutex m_gcMutex; - std::mutex m_heapMutex; - // A shared_ptr destruction path must not allow a user-program exception to escape: - // shared_ptr destruction is noexcept, so escaping would call std::terminate. - std::exception_ptr m_deferredRuntimeError; - std::mutex m_deferredRuntimeErrorMutex; - size_t m_allocSinceGc = 0; - // Buffer for echo outputs so logs (INFO/WARNING/ERROR) - // can be displayed first before normal program output. - std::vector m_echoBuffer; - struct QubitInfo { - std::string name; - bool measured; - }; - std::vector m_qubits; - std::vector m_freeQubitIndices; - // Last measured value per qubit index (-1 if never measured) - std::vector m_lastMeasurement; +// Interpreter that walks the AST and simulates quantum bits via +// QasmSimulator. It also tracks @tracked variables and defers echo output +// until warnings have been printed. +// REFACTOR: Split this monolith into a Visitor-based expression evaluator + +// Strategy pluggable backend (statevector, hardware, mock) to isolate GC, +// qubit bookkeeping, and execution policy; current single class is ~god object. +class RuntimeEvaluator { + public: + explicit RuntimeEvaluator(bool collectQasmLog = true) : m_collectQasmLog(collectQasmLog) {} + ~RuntimeEvaluator(); + void execute(Program& program); + const std::unordered_map>& measurements() const { + return m_measurements; + } + std::string getQasm() const { return m_sim.getQasm(); } + size_t heapObjectCount(); - // Core interpreter operations - Value eval(Expression* expr); - void exec(Statement* stmt); - Value call(FunctionDeclaration* fn, const std::vector& args); - Value lookup(const std::string& name); - void assign(const std::string& name, const Value& v); + private: + QasmSimulator m_sim; + bool m_collectQasmLog = true; + std::unordered_map m_functions; + struct VarEntry { + Value value; + bool tracked = false; + bool initialized = false; + }; + std::vector> m_env; + Value m_returnValue; + bool m_hasReturn = false; + std::unordered_map> m_measurements; + std::unordered_map> m_trackedCounts; + bool m_echoEnabled = true; + bool m_warnOnExit = true; + bool m_executed = false; // single-use guard + // Class runtime metadata and heap tracking + std::unordered_map> m_classTable; + std::vector> m_heap; + RuntimeClass* m_currentClassCtx = nullptr; + bool m_inStaticContext = false; + bool m_inConstructor = false; + bool m_inDestructor = false; + std::atomic m_gcRequested{false}; + std::atomic m_stopGc{false}; + bool m_gcThreadStarted = false; + std::thread m_gcThread; + std::condition_variable m_gcCv; + std::mutex m_gcMutex; + std::mutex m_heapMutex; + // A shared_ptr destruction path must not allow a user-program exception to escape: + // shared_ptr destruction is noexcept, so escaping would call std::terminate. + std::exception_ptr m_deferredRuntimeError; + std::mutex m_deferredRuntimeErrorMutex; + size_t m_allocSinceGc = 0; + // Buffer for echo outputs so logs (INFO/WARNING/ERROR) + // can be displayed first before normal program output. + std::vector m_echoBuffer; + struct QubitInfo { + std::string name; + bool measured; + }; + std::vector m_qubits; + std::vector m_freeQubitIndices; + // Last measured value per qubit index (-1 if never measured) + std::vector m_lastMeasurement; - // Qubit bookkeeping - int allocateTrackedQubit(const std::string& name); - void markMeasured(int index); - void unmarkMeasured(int index); - void ensureQubitActive(int index, int line, int column); - void ensureQubitExists(int index, int line, int column); - void warnUnmeasured() const; + // Core interpreter operations + Value eval(Expression* expr); + void exec(Statement* stmt); + Value call(FunctionDeclaration* fn, const std::vector& args); + Value lookup(const std::string& name); + void assign(const std::string& name, const Value& v); - // Class runtime helpers - RuntimeTypeInfo typeInfoFromAst(Type* type) const; - RuntimeTypeInfo typeInfoFromAst( - Type* type, const std::unordered_map& subst) const; - Value defaultValueForField(const RuntimeField& field, const std::string& ownerLabel); - void buildClassTable(Program& program); - RuntimeClass* findClass(const std::string& name) const; - RuntimeClass* instantiateGeneric(const NamedType* typeNode); - RuntimeClass* instantiateGeneric(const std::string& base, - const std::vector& args); - RuntimeClass* instantiateGeneric( - const NamedType* typeNode, - const std::unordered_map& subst); - int runtimeInheritanceDistance(const std::string& derived, const std::string& base) const; - bool isRuntimeSubclassOf(const std::string& derived, const std::string& base) const; - std::optional valueConversionCost(const RuntimeTypeInfo& expected, - const Value& actual) const; - std::optional argumentsConversionCost(const std::vector& expected, - const std::vector& actual) const; - bool valueMatchesType(const RuntimeTypeInfo& expected, const Value& actual) const; - bool argumentsMatchConstructor(const std::vector& args, - const RuntimeConstructor& candidate) const; - RuntimeMethod* findMethod(RuntimeClass* cls, const std::string& name, - const std::vector* args = nullptr); - RuntimeField* findInstanceField(RuntimeClass* cls, const std::string& name); - RuntimeField* findStaticField(RuntimeClass* cls, const std::string& name); - void initStaticFields(RuntimeClass* cls); - void ensureGcThread(); - void requestGc(); - void runCycleCollector(); - void markValue(const Value& v); - void markObject(const std::shared_ptr& obj); - void destroyObject(Object* obj, bool runUserDestructor); - void deferRuntimeError(std::exception_ptr error) noexcept; - void throwDeferredRuntimeError(); - Value callMethod(RuntimeMethod* method, RuntimeClass* staticDispatchClass, - const std::shared_ptr& receiver, const std::vector& args); - void runConstructorChain(RuntimeClass* cls, const std::shared_ptr& obj, - ConstructorDeclaration* ctor, const std::vector& args); - void runFieldInitialisers(RuntimeClass* cls, const std::shared_ptr& obj); - void recordTrackedValue(const std::string& name, const Value& v); - void releaseQubit(int index); - std::shared_ptr currentThisObject() const; + // Qubit bookkeeping + int allocateTrackedQubit(const std::string& name); + void markMeasured(int index); + void unmarkMeasured(int index); + void ensureQubitActive(int index, int line, int column); + void ensureQubitExists(int index, int line, int column); + void warnUnmeasured() const; - // Scope & output helpers - void beginScope(); - void endScope(); - void flushEchoes(); + // Class runtime helpers + RuntimeTypeInfo typeInfoFromAst(Type* type) const; + RuntimeTypeInfo typeInfoFromAst( + Type* type, const std::unordered_map& subst) const; + Value defaultValueForField(const RuntimeField& field, const std::string& ownerLabel); + void buildClassTable(Program& program); + RuntimeClass* findClass(const std::string& name) const; + RuntimeClass* instantiateGeneric(const NamedType* typeNode); + RuntimeClass* instantiateGeneric(const std::string& base, + const std::vector& args); + RuntimeClass* instantiateGeneric(const NamedType* typeNode, + const std::unordered_map& subst); + int runtimeInheritanceDistance(const std::string& derived, const std::string& base) const; + bool isRuntimeSubclassOf(const std::string& derived, const std::string& base) const; + std::optional valueConversionCost(const RuntimeTypeInfo& expected, + const Value& actual) const; + std::optional argumentsConversionCost(const std::vector& expected, + const std::vector& actual) const; + bool valueMatchesType(const RuntimeTypeInfo& expected, const Value& actual) const; + bool argumentsMatchConstructor(const std::vector& args, + const RuntimeConstructor& candidate) const; + RuntimeMethod* findMethod(RuntimeClass* cls, const std::string& name, + const std::vector* args = nullptr); + RuntimeField* findInstanceField(RuntimeClass* cls, const std::string& name); + RuntimeField* findStaticField(RuntimeClass* cls, const std::string& name); + void initStaticFields(RuntimeClass* cls); + void ensureGcThread(); + void requestGc(); + void runCycleCollector(); + void markValue(const Value& v); + void markObject(const std::shared_ptr& obj); + void destroyObject(Object* obj, bool runUserDestructor); + void deferRuntimeError(std::exception_ptr error) noexcept; + void throwDeferredRuntimeError(); + Value callMethod(RuntimeMethod* method, RuntimeClass* staticDispatchClass, + const std::shared_ptr& receiver, const std::vector& args); + void runConstructorChain(RuntimeClass* cls, const std::shared_ptr& obj, + ConstructorDeclaration* ctor, const std::vector& args); + void runFieldInitialisers(RuntimeClass* cls, const std::shared_ptr& obj); + void recordTrackedValue(const std::string& name, const Value& v); + void releaseQubit(int index); + std::shared_ptr currentThisObject() const; - public: - void setEcho(bool enabled) { m_echoEnabled = enabled; } - void setWarnOnExit(bool enabled) { m_warnOnExit = enabled; } - const auto& trackedCounts() const { return m_trackedCounts; } - // Test helper to observe whether the GC worker was started for this run. - bool gcThreadStartedForTest() const { return m_gcThreadStarted; } + // Scope & output helpers + void beginScope(); + void endScope(); + void flushEchoes(); - // Generic templates (stored by base class name without arguments) - std::unordered_map m_genericTemplates; - }; + public: + void setEcho(bool enabled) { m_echoEnabled = enabled; } + void setWarnOnExit(bool enabled) { m_warnOnExit = enabled; } + const auto& trackedCounts() const { return m_trackedCounts; } + // Test helper to observe whether the GC worker was started for this run. + bool gcThreadStartedForTest() const { return m_gcThreadStarted; } + + // Generic templates (stored by base class name without arguments) + std::unordered_map m_genericTemplates; +}; } // namespace bloch::runtime diff --git a/src/bloch/support/error/bloch_error.hpp b/src/bloch/support/error/bloch_error.hpp index 75d080b..7e09f26 100644 --- a/src/bloch/support/error/bloch_error.hpp +++ b/src/bloch/support/error/bloch_error.hpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,99 +20,99 @@ #include namespace bloch::support { - // We use simple, coloured messages to make CLI output easy to scan. - enum class MessageLevel { Info, Warning, Error }; - enum class ErrorCategory { Lexical, Parse, Semantic, Runtime, Generic }; +// We use simple, coloured messages to make CLI output easy to scan. +enum class MessageLevel { Info, Warning, Error }; +enum class ErrorCategory { Lexical, Parse, Semantic, Runtime, Generic }; - inline const char* colour(MessageLevel level) { - switch (level) { - case MessageLevel::Info: - // Green - return "\033[32m"; - case MessageLevel::Warning: - // Orange - return "\033[38;5;208m"; - case MessageLevel::Error: - default: - // Red - return "\033[31m"; - } +inline const char* colour(MessageLevel level) { + switch (level) { + case MessageLevel::Info: + // Green + return "\033[32m"; + case MessageLevel::Warning: + // Orange + return "\033[38;5;208m"; + case MessageLevel::Error: + default: + // Red + return "\033[31m"; } +} - inline const char* prefix(MessageLevel level) { - switch (level) { - case MessageLevel::Info: - return "[INFO]:"; - case MessageLevel::Warning: - return "[WARNING]:"; - case MessageLevel::Error: - default: - return "[ERROR]:"; - } +inline const char* prefix(MessageLevel level) { + switch (level) { + case MessageLevel::Info: + return "[INFO]:"; + case MessageLevel::Warning: + return "[WARNING]:"; + case MessageLevel::Error: + default: + return "[ERROR]:"; } +} - // Compose a single-line message; when line/column are 0 we omit the location. - inline std::string format(MessageLevel level, int line, int column, const std::string& msg) { - std::ostringstream err; - err << colour(level) << prefix(level) << " "; - if (line > 0 && column > 0) - err << "Line " << line << ", Col " << column << ": "; - // Reset colour before newline so subsequent output is unaffected - err << msg << "\033[0m\n"; - return err.str(); - } +// Compose a single-line message; when line/column are 0 we omit the location. +inline std::string format(MessageLevel level, int line, int column, const std::string& msg) { + std::ostringstream err; + err << colour(level) << prefix(level) << " "; + if (line > 0 && column > 0) + err << "Line " << line << ", Col " << column << ": "; + // Reset colour before newline so subsequent output is unaffected + err << msg << "\033[0m\n"; + return err.str(); +} - inline const char* categoryLabel(ErrorCategory cat) { - switch (cat) { - case ErrorCategory::Lexical: - return "Lexical error"; - case ErrorCategory::Parse: - return "Parse error"; - case ErrorCategory::Semantic: - return "Semantic error"; - case ErrorCategory::Runtime: - return "Runtime error"; - default: - return "Error"; - } +inline const char* categoryLabel(ErrorCategory cat) { + switch (cat) { + case ErrorCategory::Lexical: + return "Lexical error"; + case ErrorCategory::Parse: + return "Parse error"; + case ErrorCategory::Semantic: + return "Semantic error"; + case ErrorCategory::Runtime: + return "Runtime error"; + default: + return "Error"; } +} - inline std::string format(ErrorCategory cat, int line, int column, const std::string& msg) { - // Errors are printed in red, with a consistent "X error at L:C: ..." shape. - std::ostringstream err; - err << colour(MessageLevel::Error) << categoryLabel(cat); - if (line > 0 && column > 0) { - err << " at Ln " << line << ", Col " << column; - } - err << ": " << msg << "\033[0m\n"; - return err.str(); +inline std::string format(ErrorCategory cat, int line, int column, const std::string& msg) { + // Errors are printed in red, with a consistent "X error at L:C: ..." shape. + std::ostringstream err; + err << colour(MessageLevel::Error) << categoryLabel(cat); + if (line > 0 && column > 0) { + err << " at Ln " << line << ", Col " << column; } + err << ": " << msg << "\033[0m\n"; + return err.str(); +} - class BlochError : public std::runtime_error { - public: - BlochError(ErrorCategory category, int line, int column, const std::string& msg) - : std::runtime_error(format(category, line, column, msg)), - line(line), - column(column), - category(category) {} +class BlochError : public std::runtime_error { + public: + BlochError(ErrorCategory category, int line, int column, const std::string& msg) + : std::runtime_error(format(category, line, column, msg)), + line(line), + column(column), + category(category) {} - // default to Generic error category - BlochError(int line, int column, const std::string& msg) - : std::runtime_error(format(ErrorCategory::Generic, line, column, msg)), - line(line), - column(column), - category(ErrorCategory::Generic) {} + // default to Generic error category + BlochError(int line, int column, const std::string& msg) + : std::runtime_error(format(ErrorCategory::Generic, line, column, msg)), + line(line), + column(column), + category(ErrorCategory::Generic) {} - int line; - int column; - ErrorCategory category; - }; + int line; + int column; + ErrorCategory category; +}; - inline void blochInfo(int line, int column, const std::string& msg) { - std::cerr << format(MessageLevel::Info, line, column, msg); - } +inline void blochInfo(int line, int column, const std::string& msg) { + std::cerr << format(MessageLevel::Info, line, column, msg); +} - inline void blochWarning(int line, int column, const std::string& msg) { - std::cerr << format(MessageLevel::Warning, line, column, msg); - } +inline void blochWarning(int line, int column, const std::string& msg) { + std::cerr << format(MessageLevel::Warning, line, column, msg); +} } // namespace bloch::support diff --git a/src/bloch/update/update_manager.cpp b/src/bloch/update/update_manager.cpp deleted file mode 100644 index 0e042fb..0000000 --- a/src/bloch/update/update_manager.cpp +++ /dev/null @@ -1,780 +0,0 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "bloch/update/update_manager.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef CPPHTTPLIB_OPENSSL_SUPPORT -#define CPPHTTPLIB_OPENSSL_SUPPORT -#endif -#include -#include "third_party/cpp-httplib/httplib.h" - -namespace bloch::update { - namespace { - - // REFACTOR: Wrap filesystem/HTTP/time dependencies behind interfaces - // (Strategy) so we can unit-test update logic without hitting disk/network - // and swap out curl/httplib or platform-specific cache paths cleanly. - - using Clock = std::chrono::system_clock; - constexpr auto kUpdateWindow = std::chrono::hours(72); - constexpr std::string_view kChangelogUrl = - "https://github.com/bloch-labs/bloch/blob/master/CHANGELOG.md"; - - struct UpdateCache { - std::string latestVersion; - Clock::time_point lastChecked{}; - Clock::time_point lastNotified{}; - }; - - struct SemVer { - int major{0}; - int minor{0}; - int patch{0}; - bool valid{false}; - }; - - std::string userAgent(const std::string& currentVersion) { - if (currentVersion.empty()) - return "bloch"; - return "bloch/" + currentVersion; - } - - std::filesystem::path cacheFilePath() { - if (const char* xdg = std::getenv("XDG_CACHE_HOME"); xdg && *xdg) { - return std::filesystem::path(xdg) / "bloch" / "update_cache.txt"; - } -#ifdef _WIN32 - if (const char* local = std::getenv("LOCALAPPDATA"); local && *local) { - return std::filesystem::path(local) / "Bloch" / "update_cache.txt"; - } -#endif - if (const char* home = std::getenv("HOME"); home && *home) { - return std::filesystem::path(home) / ".cache" / "bloch" / "update_cache.txt"; - } - return std::filesystem::temp_directory_path() / "bloch-update-cache.txt"; - } - - UpdateCache emptyCache() { - return UpdateCache{std::string(), Clock::time_point{}, Clock::time_point{}}; - } - - std::optional loadCache() { - const auto path = cacheFilePath(); - std::ifstream in(path); - if (!in) - return std::nullopt; - - std::string checkedStr; - std::string latest; - std::string notifiedStr; - if (!std::getline(in, checkedStr)) - return std::nullopt; - if (!std::getline(in, latest)) - return std::nullopt; - if (!std::getline(in, notifiedStr)) - notifiedStr = "0"; - - try { - auto checkedSec = std::stoll(checkedStr); - auto notifiedSec = std::stoll(notifiedStr.empty() ? "0" : notifiedStr); - UpdateCache cache; - cache.latestVersion = latest; - cache.lastChecked = Clock::time_point(std::chrono::seconds(checkedSec)); - cache.lastNotified = Clock::time_point(std::chrono::seconds(notifiedSec)); - return cache; - } catch (...) { - return std::nullopt; - } - } - - void saveCache(const UpdateCache& cache) { - const auto path = cacheFilePath(); - std::error_code ec; - std::filesystem::create_directories(path.parent_path(), ec); - - std::ofstream out(path, std::ios::trunc); - if (!out) - return; - - const auto toSeconds = [](Clock::time_point tp) { - return std::chrono::duration_cast(tp.time_since_epoch()) - .count(); - }; - - out << toSeconds(cache.lastChecked) << "\n"; - out << cache.latestVersion << "\n"; - out << toSeconds(cache.lastNotified) << "\n"; - } - - SemVer parseSemVer(const std::string& version) { - SemVer sem; - if (version.empty()) - return sem; - std::string v = version; - if (!v.empty() && v.front() == 'v') - v.erase(v.begin()); - - size_t pos = 0; - int idx = 0; - while (pos < v.size() && idx < 3) { - size_t start = pos; - while (pos < v.size() && std::isdigit(static_cast(v[pos]))) { - ++pos; - } - if (start == pos) - break; - int value = std::stoi(v.substr(start, pos - start)); - if (idx == 0) - sem.major = value; - else if (idx == 1) - sem.minor = value; - else - sem.patch = value; - sem.valid = true; - ++idx; - if (pos >= v.size() || v[pos] != '.') - break; - ++pos; - } - return sem; - } - - int compareSemVer(const SemVer& current, const SemVer& latest) { - if (!current.valid || !latest.valid) - return 0; - if (current.major != latest.major) - return current.major < latest.major ? -1 : 1; - if (current.minor != latest.minor) - return current.minor < latest.minor ? -1 : 1; - if (current.patch != latest.patch) - return current.patch < latest.patch ? -1 : 1; - return 0; - } - - std::string changeLabel(const SemVer& current, const SemVer& latest) { - if (!current.valid || !latest.valid) - return "new"; - if (latest.major > current.major) - return "major"; - if (latest.minor > current.minor) - return "minor"; - if (latest.patch > current.patch) - return "patch"; - return "new"; - } - - bool hasExpired(const Clock::time_point& tp, Clock::time_point now) { - return now - tp >= kUpdateWindow; - } - - std::optional extractTagName(const std::string& body) { - const std::string needle = "\"tag_name\""; - auto pos = body.find(needle); - if (pos == std::string::npos) - return std::nullopt; - pos = body.find(':', pos); - if (pos == std::string::npos) - return std::nullopt; - pos = body.find('"', pos); - if (pos == std::string::npos) - return std::nullopt; - auto end = body.find('"', pos + 1); - if (end == std::string::npos) - return std::nullopt; - return body.substr(pos + 1, end - pos - 1); - } - - std::string describeError(httplib::Error err) { - switch (err) { - case httplib::Error::Success: - return "success"; - case httplib::Error::Unknown: - return "unknown error"; - case httplib::Error::Connection: - return "connection error"; - case httplib::Error::BindIPAddress: - return "bind error"; - case httplib::Error::Read: - return "read error"; - case httplib::Error::Write: - return "write error"; - case httplib::Error::ExceedRedirectCount: - return "too many redirects"; - case httplib::Error::Canceled: - return "request cancelled"; - case httplib::Error::SSLConnection: - return "ssl connection error"; - case httplib::Error::SSLLoadingCerts: - return "ssl certificate load error"; - case httplib::Error::SSLServerVerification: - return "ssl verification failed"; - case httplib::Error::UnsupportedMultipartBoundaryChars: - return "unsupported multipart boundary"; - default: - return "http client error"; - } - } - - void configureClient(httplib::SSLClient& client) { - client.set_follow_location(true); - client.set_connection_timeout(2, 0); // fast-fail on slow DNS/connect - client.set_read_timeout(15, 0); - client.set_write_timeout(15, 0); - } - - std::optional fetchLatestReleaseTag(const std::string& agent, - std::string& error) { - httplib::SSLClient client("api.github.com"); - configureClient(client); - httplib::Headers headers{ - {"User-Agent", agent}, - {"Accept", "application/vnd.github+json"}, - }; - auto res = client.Get("/repos/bloch-labs/bloch/releases/latest", headers); - if (!res) { - error = describeError(res.error()); - return std::nullopt; - } - if (res->status != 200) { - error = "status " + std::to_string(res->status); - return std::nullopt; - } - auto tag = extractTagName(res->body); - if (!tag) { - error = "missing tag_name"; - return std::nullopt; - } - return tag; - } - - bool shouldSkipChecks() { - return std::getenv("BLOCH_NO_UPDATE_CHECK") || std::getenv("CI") || - std::getenv("BLOCH_OFFLINE"); - } - - bool maybePrintNotice(const std::string& latestVersion, const std::string& currentVersion, - Clock::time_point now, UpdateCache& cache) { - if (latestVersion.empty()) - return false; - if (!hasExpired(cache.lastNotified, now)) - return false; - - const auto current = parseSemVer(currentVersion); - const auto latest = parseSemVer(latestVersion); - if (!current.valid || !latest.valid) - return false; - if (compareSemVer(current, latest) >= 0) - return false; - - const auto label = changeLabel(current, latest); - std::cout << "There is a new " << label << " version of Bloch, " << latestVersion - << ". You currently have " << currentVersion - << ". To install the latest run bloch --update." << std::endl; - cache.lastNotified = now; - cache.latestVersion = latestVersion; - return true; - } - - std::filesystem::path resolveInstallPath(const std::string& argv0) { -#ifdef __linux__ - std::error_code ec; - auto exePath = std::filesystem::read_symlink("/proc/self/exe", ec); - if (!ec) - return exePath; -#endif - if (!argv0.empty()) { - std::error_code ec; - auto canonical = std::filesystem::canonical(argv0, ec); - if (!ec) - return canonical; - auto absolute = std::filesystem::absolute(argv0, ec); - if (!ec) - return absolute; - } - if (const char* home = std::getenv("HOME"); home && *home) { - return std::filesystem::path(home) / ".local" / "bin" / "bloch"; - } - return std::filesystem::path("bloch"); - } - - std::filesystem::path resolveStdlibRootPath() { - if (const char* overridePath = std::getenv("BLOCH_STDLIB_PATH"); - overridePath && *overridePath) { - return std::filesystem::path(overridePath); - } -#ifdef _WIN32 - if (const char* local = std::getenv("LOCALAPPDATA"); local && *local) { - return std::filesystem::path(local) / "Bloch" / "library"; - } -#elif defined(__APPLE__) - if (const char* home = std::getenv("HOME"); home && *home) { - return std::filesystem::path(home) / "Library" / "Application Support" / "Bloch" / - "library"; - } -#else - std::filesystem::path dataRoot; - if (const char* xdg = std::getenv("XDG_DATA_HOME"); xdg && *xdg) { - dataRoot = std::filesystem::path(xdg); - } else if (const char* home = std::getenv("HOME"); home && *home) { - dataRoot = std::filesystem::path(home) / ".local" / "share"; - } - if (!dataRoot.empty()) { - return dataRoot / "bloch" / "library"; - } -#endif - return {}; - } - - std::optional findBundledLibraryRoot( - const std::filesystem::path& extractedRoot) { - std::error_code ec; - for (auto it = std::filesystem::recursive_directory_iterator(extractedRoot, ec); - it != std::filesystem::recursive_directory_iterator(); it.increment(ec)) { - if (ec) - break; - if (!it->is_directory(ec)) - continue; - const auto path = it->path(); - if (path.filename() != "library") - continue; - auto parent = path.parent_path(); - if (parent.filename() == "bloch" && parent.parent_path().filename() == "share") - return path; - } - return std::nullopt; - } - - bool copyDirectoryContents(const std::filesystem::path& source, - const std::filesystem::path& destination, std::string& error) { - std::error_code ec; - std::filesystem::create_directories(destination, ec); - if (ec) { - error = "failed creating directory '" + destination.string() + "'"; - return false; - } - for (const auto& entry : std::filesystem::directory_iterator(source, ec)) { - if (ec) { - error = "failed iterating '" + source.string() + "'"; - return false; - } - const auto target = destination / entry.path().filename(); - std::filesystem::copy(entry.path(), target, - std::filesystem::copy_options::recursive | - std::filesystem::copy_options::overwrite_existing, - ec); - if (ec) { - error = "failed copying '" + entry.path().string() + "' to '" + - target.string() + "'"; - return false; - } - } - return true; - } - - bool installBundledStdlib(const std::filesystem::path& extractedRoot, - const std::string& version, std::string& error) { - auto bundled = findBundledLibraryRoot(extractedRoot); - if (!bundled) { - error = "bundled stdlib not found in release archive"; - return false; - } - auto stdlibRoot = resolveStdlibRootPath(); - if (stdlibRoot.empty()) { - error = "unable to resolve stdlib install root"; - return false; - } - auto versioned = stdlibRoot / version; - std::error_code ec; - std::filesystem::remove_all(versioned, ec); - if (!copyDirectoryContents(*bundled, stdlibRoot, error)) - return false; - if (!copyDirectoryContents(*bundled, versioned, error)) - return false; - return true; - } - - bool downloadText(const std::string& host, const std::string& path, - const std::string& agent, std::string& out, std::string& error) { - httplib::SSLClient client(host); - configureClient(client); - httplib::Headers headers{{"User-Agent", agent}}; - auto res = client.Get(path.c_str(), headers); - if (!res) { - error = describeError(res.error()); - return false; - } - if (res->status < 200 || res->status >= 300) { - error = "status " + std::to_string(res->status); - return false; - } - out = res->body; - return true; - } - - bool downloadFile(const std::string& host, const std::string& path, - const std::string& agent, const std::filesystem::path& dest, - std::string& error) { - httplib::SSLClient client(host); - configureClient(client); - httplib::Headers headers{{"User-Agent", agent}}; - std::ofstream out(dest, std::ios::binary | std::ios::trunc); - if (!out) { - error = "cannot open download destination"; - return false; - } - - auto res = client.Get(path.c_str(), headers, [&](const char* data, size_t len) { - out.write(data, static_cast(len)); - return static_cast(out); - }); - if (!out) { - error = "failed while writing to disk"; - return false; - } - if (!res) { - error = describeError(res.error()); - return false; - } - if (res->status < 200 || res->status >= 300) { - error = "status " + std::to_string(res->status); - return false; - } - return true; - } - - std::string sha256File(const std::filesystem::path& file, std::string& error) { - std::ifstream in(file, std::ios::binary); - if (!in) { - error = "unable to open " + file.string(); - return {}; - } - - std::unique_ptr ctx(EVP_MD_CTX_new(), - EVP_MD_CTX_free); - if (!ctx) { - error = "unable to allocate digest context"; - return {}; - } - if (EVP_DigestInit_ex(ctx.get(), EVP_sha256(), nullptr) != 1) { - error = "unable to initialise digest context"; - return {}; - } - - char buffer[8192]; - while (in.good()) { - in.read(buffer, sizeof(buffer)); - std::streamsize read = in.gcount(); - if (read > 0 && - EVP_DigestUpdate(ctx.get(), buffer, static_cast(read)) != 1) { - error = "failed hashing " + file.string(); - return {}; - } - } - if (in.bad()) { - error = "failed reading " + file.string(); - return {}; - } - unsigned char hash[EVP_MAX_MD_SIZE]; - unsigned int hashLength = 0; - if (EVP_DigestFinal_ex(ctx.get(), hash, &hashLength) != 1) { - error = "failed finalising digest"; - return {}; - } - std::ostringstream oss; - oss << std::hex << std::setfill('0'); - for (unsigned int i = 0; i < hashLength; ++i) { - oss << std::setw(2) << static_cast(hash[i]); - } - return oss.str(); - } - - std::optional parseChecksum(const std::string& content, - const std::string& assetName) { - std::istringstream in(content); - std::string line; - while (std::getline(in, line)) { - if (line.find(assetName) == std::string::npos) - continue; - std::istringstream parts(line); - std::string hash; - if (parts >> hash) - return hash; - } - return std::nullopt; - } - - bool extractArchive(const std::filesystem::path& archive, const std::filesystem::path& dest, - std::string& error) { - std::error_code ec; - std::filesystem::create_directories(dest, ec); - std::ostringstream cmd; - cmd << "tar -xzf \"" << archive.string() << "\" -C \"" << dest.string() << "\""; - int rc = std::system(cmd.str().c_str()); - if (rc != 0) { - error = "tar exited with code " + std::to_string(rc); - return false; - } - return true; - } - - std::optional findBinary(const std::filesystem::path& root) { - std::error_code ec; - for (auto it = std::filesystem::recursive_directory_iterator(root, ec); - it != std::filesystem::recursive_directory_iterator(); it.increment(ec)) { - if (ec) - break; - if (it->is_regular_file() && it->path().filename() == "bloch") { - return it->path(); - } - } - return std::nullopt; - } - - std::string osLabel() { -#if defined(__APPLE__) - return "macOS"; -#elif defined(_WIN32) - return "Windows"; -#else - return "Linux"; -#endif - } - - std::string archLabel() { -#if defined(__x86_64__) || defined(_M_X64) - return "X64"; -#elif defined(__aarch64__) || defined(_M_ARM64) - return "ARM64"; -#else - return {}; -#endif - } - - bool hasLatest(const std::string& currentVersion, const std::string& latestVersion) { - const auto current = parseSemVer(currentVersion); - const auto latest = parseSemVer(latestVersion); - if (!current.valid || !latest.valid) - return false; - return compareSemVer(current, latest) >= 0; - } - - struct TempDirGuard { - std::filesystem::path path; - explicit TempDirGuard(std::filesystem::path p) : path(std::move(p)) {} - ~TempDirGuard() { - if (path.empty()) - return; - std::error_code ec; - std::filesystem::remove_all(path, ec); - } - }; - - } // namespace - - void checkForUpdatesIfDue(const std::string& currentVersion) { - if (shouldSkipChecks()) - return; - - const auto now = Clock::now(); - auto cached = loadCache(); - UpdateCache cache = cached.value_or(emptyCache()); - - if (cached && hasExpired(cache.lastChecked, now) == false) { - if (!cache.latestVersion.empty() && - maybePrintNotice(cache.latestVersion, currentVersion, now, cache)) { - saveCache(cache); - } - return; - } - - // Use any cached version info before hitting the network. - if (cached && !cache.latestVersion.empty()) { - if (maybePrintNotice(cache.latestVersion, currentVersion, now, cache)) - saveCache(cache); - } - - std::string err; - auto latest = fetchLatestReleaseTag(userAgent(currentVersion), err); - if (!latest) - return; - - cache.latestVersion = *latest; - cache.lastChecked = now; - maybePrintNotice(*latest, currentVersion, now, cache); - saveCache(cache); - } - - bool performSelfUpdate(const std::string& currentVersion, const std::string& argv0) { - std::string err; - auto latest = fetchLatestReleaseTag(userAgent(currentVersion), err); - if (!latest) { - std::cerr << "Unable to resolve latest Bloch release from GitHub (" << err << ")." - << std::endl; - return false; - } - if (hasLatest(currentVersion, *latest)) { - std::cout << "You already have the latest Bloch release (" << *latest << ")." - << std::endl; - return true; - } - - const auto currentSem = parseSemVer(currentVersion); - const auto latestSem = parseSemVer(*latest); - if (currentSem.valid && latestSem.valid && latestSem.major > currentSem.major) { - std::cout << "A major Bloch update is available (" << currentVersion << " -> " - << *latest << "). Review changes: " << kChangelogUrl - << "\nProceed with the update? [y/N]: " << std::flush; - std::string answer; - std::getline(std::cin, answer); - if (!(answer == "y" || answer == "Y" || answer == "yes" || answer == "YES")) { - std::cout << "Update cancelled." << std::endl; - return false; - } - } - -#ifdef _WIN32 - std::ostringstream cmd; - cmd << "powershell -NoProfile -ExecutionPolicy Bypass -Command \"" - << "$ErrorActionPreference='Stop';" - << "$url='https://raw.githubusercontent.com/bloch-labs/bloch/HEAD/scripts/install.ps1';" - << "$out=Join-Path $env:TEMP 'bloch-update.ps1';" - << "Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $out;" - << "$ver='" << *latest << "';" - << "& $out -Version $ver;" - << "\""; - int rc = std::system(cmd.str().c_str()); - if (rc != 0) { - std::cerr << "Failed to run Windows updater (exit code " << rc - << "). Try reinstalling via the latest PowerShell installer." << std::endl; - return false; - } - - UpdateCache cache = emptyCache(); - cache.latestVersion = *latest; - cache.lastChecked = Clock::now(); - cache.lastNotified = cache.lastChecked; - saveCache(cache); - - std::cout << "Bloch updated to " << *latest << " via the PowerShell installer script." - << std::endl; - return true; -#else - - const auto os = osLabel(); - const auto arch = archLabel(); - if (os.empty() || arch.empty()) { - std::cerr << "Unsupported platform for self-update (os=" << os << ", arch=" << arch - << ")." << std::endl; - return false; - } - - const auto assetName = "bloch-" + *latest + "-" + os + "-" + arch + ".tar.gz"; - const auto basePath = "/bloch-labs/bloch/releases/download/" + *latest; // host: github.com - - const auto tempDir = - std::filesystem::temp_directory_path() / - ("bloch-update-" + std::to_string(std::chrono::duration_cast( - Clock::now().time_since_epoch()) - .count())); - TempDirGuard cleanup(tempDir); - std::error_code ec; - std::filesystem::create_directories(tempDir, ec); - const auto archivePath = tempDir / assetName; - - if (!downloadFile("github.com", basePath + "/" + assetName, userAgent(currentVersion), - archivePath, err)) { - std::cerr << "Failed to download " << assetName << " (" << err << ")." << std::endl; - return false; - } - - std::string checksums; - if (downloadText("github.com", basePath + "/checksums.txt", userAgent(currentVersion), - checksums, err)) { - auto expected = parseChecksum(checksums, assetName); - if (expected) { - std::string hashErr; - auto actual = sha256File(archivePath, hashErr); - if (actual.empty()) { - std::cerr << "Failed to compute checksum: " << hashErr << std::endl; - return false; - } - if (*expected != actual) { - std::cerr << "Checksum mismatch for " << assetName << std::endl; - return false; - } - } - } - - if (!extractArchive(archivePath, tempDir, err)) { - std::cerr << "Failed to extract archive: " << err << std::endl; - return false; - } - - auto newBinary = findBinary(tempDir); - if (!newBinary) { - std::cerr << "Unable to locate the bloch binary inside the downloaded archive." - << std::endl; - return false; - } - - const auto installPath = resolveInstallPath(argv0); - std::filesystem::create_directories(installPath.parent_path(), ec); - std::filesystem::permissions( - *newBinary, - std::filesystem::perms::owner_read | std::filesystem::perms::owner_write | - std::filesystem::perms::owner_exec | std::filesystem::perms::group_read | - std::filesystem::perms::group_exec | std::filesystem::perms::others_read | - std::filesystem::perms::others_exec, - std::filesystem::perm_options::add, ec); - - std::filesystem::copy_file(*newBinary, installPath, - std::filesystem::copy_options::overwrite_existing, ec); - if (ec) { - std::cerr << "Failed to install the new binary to " << installPath << ": " - << ec.message() << std::endl; - return false; - } - - std::string stdlibErr; - if (!installBundledStdlib(tempDir, *latest, stdlibErr)) { - std::cerr << "Warning: " << stdlibErr << std::endl; - } - - UpdateCache cache = emptyCache(); - cache.latestVersion = *latest; - cache.lastChecked = Clock::now(); - cache.lastNotified = cache.lastChecked; - saveCache(cache); - - std::cout << "Bloch updated to " << *latest << " at " << installPath << std::endl; - return true; -#endif - } - -} // namespace bloch::update diff --git a/src/bloch/update/update_manager.hpp b/src/bloch/update/update_manager.hpp deleted file mode 100644 index 9ac16d0..0000000 --- a/src/bloch/update/update_manager.hpp +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#pragma once - -#include - -namespace bloch::update { - // Run a lightweight update check (no more than once every 72 hours) and - // print a single notice if a newer version exists. - void checkForUpdatesIfDue(const std::string& currentVersion); - - // Download and install the latest Bloch release. Returns true on success. - bool performSelfUpdate(const std::string& currentVersion, const std::string& argv0); -} // namespace bloch::update diff --git a/src/main.cpp b/src/main.cpp index 0076d82..bfa51f3 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/src/third_party/cpp-httplib/LICENSE b/src/third_party/cpp-httplib/LICENSE deleted file mode 100644 index 3e5ed35..0000000 --- a/src/third_party/cpp-httplib/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2017 yhirose - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/src/third_party/cpp-httplib/httplib.h b/src/third_party/cpp-httplib/httplib.h deleted file mode 100644 index 0892756..0000000 --- a/src/third_party/cpp-httplib/httplib.h +++ /dev/null @@ -1,12380 +0,0 @@ -// -// httplib.h -// -// Copyright (c) 2025 Yuji Hirose. All rights reserved. -// MIT License -// - -#ifndef CPPHTTPLIB_HTTPLIB_H -#define CPPHTTPLIB_HTTPLIB_H - -#define CPPHTTPLIB_VERSION "0.28.0" -#define CPPHTTPLIB_VERSION_NUM "0x001C00" - -/* - * Platform compatibility check - */ - -#if defined(_WIN32) && !defined(_WIN64) -#if defined(_MSC_VER) -#pragma message("cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler.") -#else -#warning "cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler." -#endif -#elif defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ < 8 -#warning "cpp-httplib doesn't support 32-bit platforms. Please use a 64-bit compiler." -#elif defined(__SIZEOF_SIZE_T__) && __SIZEOF_SIZE_T__ < 8 -#warning "cpp-httplib doesn't support platforms where size_t is less than 64 bits." -#endif - -#ifdef _WIN32 -#if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00 -#error "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later." -#endif -#endif - -/* - * Configuration - */ - -#ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND -#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5 -#endif - -#ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND -#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000 -#endif - -#ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT -#define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100 -#endif - -#ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND -#define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300 -#endif - -#ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND -#define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0 -#endif - -#ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND -#define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5 -#endif - -#ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND -#define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0 -#endif - -#ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND -#define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5 -#endif - -#ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND -#define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0 -#endif - -#ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND -#define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300 -#endif - -#ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND -#define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0 -#endif - -#ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND -#define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5 -#endif - -#ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND -#define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0 -#endif - -#ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND -#define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0 -#endif - -#ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND -#define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0 -#endif - -#ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND -#ifdef _WIN32 -#define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000 -#else -#define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0 -#endif -#endif - -#ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH -#define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192 -#endif - -#ifndef CPPHTTPLIB_HEADER_MAX_LENGTH -#define CPPHTTPLIB_HEADER_MAX_LENGTH 8192 -#endif - -#ifndef CPPHTTPLIB_HEADER_MAX_COUNT -#define CPPHTTPLIB_HEADER_MAX_COUNT 100 -#endif - -#ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT -#define CPPHTTPLIB_REDIRECT_MAX_COUNT 20 -#endif - -#ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT -#define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024 -#endif - -#ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH -#define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits::max)()) -#endif - -#ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH -#define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192 -#endif - -#ifndef CPPHTTPLIB_RANGE_MAX_COUNT -#define CPPHTTPLIB_RANGE_MAX_COUNT 1024 -#endif - -#ifndef CPPHTTPLIB_TCP_NODELAY -#define CPPHTTPLIB_TCP_NODELAY false -#endif - -#ifndef CPPHTTPLIB_IPV6_V6ONLY -#define CPPHTTPLIB_IPV6_V6ONLY false -#endif - -#ifndef CPPHTTPLIB_RECV_BUFSIZ -#define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u) -#endif - -#ifndef CPPHTTPLIB_SEND_BUFSIZ -#define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u) -#endif - -#ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ -#define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u) -#endif - -#ifndef CPPHTTPLIB_THREAD_POOL_COUNT -#define CPPHTTPLIB_THREAD_POOL_COUNT \ - ((std::max)(8u, std::thread::hardware_concurrency() > 0 \ - ? std::thread::hardware_concurrency() - 1 \ - : 0)) -#endif - -#ifndef CPPHTTPLIB_RECV_FLAGS -#define CPPHTTPLIB_RECV_FLAGS 0 -#endif - -#ifndef CPPHTTPLIB_SEND_FLAGS -#define CPPHTTPLIB_SEND_FLAGS 0 -#endif - -#ifndef CPPHTTPLIB_LISTEN_BACKLOG -#define CPPHTTPLIB_LISTEN_BACKLOG 5 -#endif - -#ifndef CPPHTTPLIB_MAX_LINE_LENGTH -#define CPPHTTPLIB_MAX_LINE_LENGTH 32768 -#endif - -/* - * Headers - */ - -#ifdef _WIN32 -#ifndef _CRT_SECURE_NO_WARNINGS -#define _CRT_SECURE_NO_WARNINGS -#endif //_CRT_SECURE_NO_WARNINGS - -#ifndef _CRT_NONSTDC_NO_DEPRECATE -#define _CRT_NONSTDC_NO_DEPRECATE -#endif //_CRT_NONSTDC_NO_DEPRECATE - -#if defined(_MSC_VER) -#if _MSC_VER < 1900 -#error Sorry, Visual Studio versions prior to 2015 are not supported -#endif - -#pragma comment(lib, "ws2_32.lib") - -using ssize_t = __int64; -#endif // _MSC_VER - -#ifndef S_ISREG -#define S_ISREG(m) (((m)&S_IFREG) == S_IFREG) -#endif // S_ISREG - -#ifndef S_ISDIR -#define S_ISDIR(m) (((m)&S_IFDIR) == S_IFDIR) -#endif // S_ISDIR - -#ifndef NOMINMAX -#define NOMINMAX -#endif // NOMINMAX - -#include -#include -#include - -#if defined(__has_include) -#if __has_include() -// afunix.h uses types declared in winsock2.h, so has to be included after it. -#include -#define CPPHTTPLIB_HAVE_AFUNIX_H 1 -#endif -#endif - -#ifndef WSA_FLAG_NO_HANDLE_INHERIT -#define WSA_FLAG_NO_HANDLE_INHERIT 0x80 -#endif - -using nfds_t = unsigned long; -using socket_t = SOCKET; -using socklen_t = int; - -#else // not _WIN32 - -#include -#if !defined(_AIX) && !defined(__MVS__) -#include -#endif -#ifdef __MVS__ -#include -#ifndef NI_MAXHOST -#define NI_MAXHOST 1025 -#endif -#endif -#include -#include -#include -#ifdef __linux__ -#include -#undef _res // Undefine _res macro to avoid conflicts with user code (#2278) -#endif -#include -#include -#include -#include -#include -#include -#include -#include - -using socket_t = int; -#ifndef INVALID_SOCKET -#define INVALID_SOCKET (-1) -#endif -#endif //_WIN32 - -#if defined(__APPLE__) -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \ - defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) -#if TARGET_OS_MAC -#include -#include -#endif -#endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO or - // CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT -#ifdef _WIN32 -#include - -// these are defined in wincrypt.h and it breaks compilation if BoringSSL is -// used -#undef X509_NAME -#undef X509_CERT_PAIR -#undef X509_EXTENSIONS -#undef PKCS7_SIGNER_INFO - -#ifdef _MSC_VER -#pragma comment(lib, "crypt32.lib") -#endif -#endif // _WIN32 - -#if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) -#if TARGET_OS_MAC -#include -#endif -#endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO - -#include -#include -#include -#include - -#if defined(_WIN32) && defined(OPENSSL_USE_APPLINK) -#include -#endif - -#include -#include - -#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER) -#if OPENSSL_VERSION_NUMBER < 0x1010107f -#error Please use OpenSSL or a current version of BoringSSL -#endif -#define SSL_get1_peer_certificate SSL_get_peer_certificate -#elif OPENSSL_VERSION_NUMBER < 0x30000000L -#error Sorry, OpenSSL versions prior to 3.0.0 are not supported -#endif - -#endif // CPPHTTPLIB_OPENSSL_SUPPORT - -#ifdef CPPHTTPLIB_ZLIB_SUPPORT -#include -#endif - -#ifdef CPPHTTPLIB_BROTLI_SUPPORT -#include -#include -#endif - -#ifdef CPPHTTPLIB_ZSTD_SUPPORT -#include -#endif - -/* - * Declaration - */ -namespace httplib { - - namespace detail { - - /* - * Backport std::make_unique from C++14. - * - * NOTE: This code came up with the following stackoverflow post: - * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique - * - */ - - template - typename std::enable_if::value, std::unique_ptr>::type make_unique( - Args&&... args) { - return std::unique_ptr(new T(std::forward(args)...)); - } - - template - typename std::enable_if::value, std::unique_ptr>::type make_unique( - std::size_t n) { - typedef typename std::remove_extent::type RT; - return std::unique_ptr(new RT[n]); - } - - namespace case_ignore { - - inline unsigned char to_lower(int c) { - const static unsigned char table[256] = { - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, - 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 91, 92, 93, 94, 95, - 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, - 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, - 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, - 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, - 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, - 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, - 240, 241, 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, - 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, - 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, - }; - return table[(unsigned char)(char)c]; - } - - inline bool equal(const std::string& a, const std::string& b) { - return a.size() == b.size() && - std::equal(a.begin(), a.end(), b.begin(), - [](char ca, char cb) { return to_lower(ca) == to_lower(cb); }); - } - - struct equal_to { - bool operator()(const std::string& a, const std::string& b) const { - return equal(a, b); - } - }; - - struct hash { - size_t operator()(const std::string& key) const { - return hash_core(key.data(), key.size(), 0); - } - - size_t hash_core(const char* s, size_t l, size_t h) const { - return (l == 0) - ? h - : hash_core(s + 1, l - 1, - // Unsets the 6 high bits of h, therefore no - // overflow happens - (((std::numeric_limits::max)() >> 6) & h * 33) ^ - static_cast(to_lower(*s))); - } - }; - - template - using unordered_set = - std::unordered_set; - - } // namespace case_ignore - - // This is based on - // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189". - - struct scope_exit { - explicit scope_exit(std::function&& f) - : exit_function(std::move(f)), execute_on_destruction{true} {} - - scope_exit(scope_exit&& rhs) noexcept - : exit_function(std::move(rhs.exit_function)), - execute_on_destruction{rhs.execute_on_destruction} { - rhs.release(); - } - - ~scope_exit() { - if (execute_on_destruction) { - this->exit_function(); - } - } - - void release() { this->execute_on_destruction = false; } - - private: - scope_exit(const scope_exit&) = delete; - void operator=(const scope_exit&) = delete; - scope_exit& operator=(scope_exit&&) = delete; - - std::function exit_function; - bool execute_on_destruction; - }; - - } // namespace detail - - enum SSLVerifierResponse { - // no decision has been made, use the built-in certificate verifier - NoDecisionMade, - // connection certificate is verified and accepted - CertificateAccepted, - // connection certificate was processed but is rejected - CertificateRejected - }; - - enum StatusCode { - // Information responses - Continue_100 = 100, - SwitchingProtocol_101 = 101, - Processing_102 = 102, - EarlyHints_103 = 103, - - // Successful responses - OK_200 = 200, - Created_201 = 201, - Accepted_202 = 202, - NonAuthoritativeInformation_203 = 203, - NoContent_204 = 204, - ResetContent_205 = 205, - PartialContent_206 = 206, - MultiStatus_207 = 207, - AlreadyReported_208 = 208, - IMUsed_226 = 226, - - // Redirection messages - MultipleChoices_300 = 300, - MovedPermanently_301 = 301, - Found_302 = 302, - SeeOther_303 = 303, - NotModified_304 = 304, - UseProxy_305 = 305, - unused_306 = 306, - TemporaryRedirect_307 = 307, - PermanentRedirect_308 = 308, - - // Client error responses - BadRequest_400 = 400, - Unauthorized_401 = 401, - PaymentRequired_402 = 402, - Forbidden_403 = 403, - NotFound_404 = 404, - MethodNotAllowed_405 = 405, - NotAcceptable_406 = 406, - ProxyAuthenticationRequired_407 = 407, - RequestTimeout_408 = 408, - Conflict_409 = 409, - Gone_410 = 410, - LengthRequired_411 = 411, - PreconditionFailed_412 = 412, - PayloadTooLarge_413 = 413, - UriTooLong_414 = 414, - UnsupportedMediaType_415 = 415, - RangeNotSatisfiable_416 = 416, - ExpectationFailed_417 = 417, - ImATeapot_418 = 418, - MisdirectedRequest_421 = 421, - UnprocessableContent_422 = 422, - Locked_423 = 423, - FailedDependency_424 = 424, - TooEarly_425 = 425, - UpgradeRequired_426 = 426, - PreconditionRequired_428 = 428, - TooManyRequests_429 = 429, - RequestHeaderFieldsTooLarge_431 = 431, - UnavailableForLegalReasons_451 = 451, - - // Server error responses - InternalServerError_500 = 500, - NotImplemented_501 = 501, - BadGateway_502 = 502, - ServiceUnavailable_503 = 503, - GatewayTimeout_504 = 504, - HttpVersionNotSupported_505 = 505, - VariantAlsoNegotiates_506 = 506, - InsufficientStorage_507 = 507, - LoopDetected_508 = 508, - NotExtended_510 = 510, - NetworkAuthenticationRequired_511 = 511, - }; - - using Headers = std::unordered_multimap; - - using Params = std::multimap; - using Match = std::smatch; - - using DownloadProgress = std::function; - using UploadProgress = std::function; - - struct Response; - using ResponseHandler = std::function; - - struct FormData { - std::string name; - std::string content; - std::string filename; - std::string content_type; - Headers headers; - }; - - struct FormField { - std::string name; - std::string content; - Headers headers; - }; - using FormFields = std::multimap; - - using FormFiles = std::multimap; - - struct MultipartFormData { - FormFields fields; // Text fields from multipart - FormFiles files; // Files from multipart - - // Text field access - std::string get_field(const std::string& key, size_t id = 0) const; - std::vector get_fields(const std::string& key) const; - bool has_field(const std::string& key) const; - size_t get_field_count(const std::string& key) const; - - // File access - FormData get_file(const std::string& key, size_t id = 0) const; - std::vector get_files(const std::string& key) const; - bool has_file(const std::string& key) const; - size_t get_file_count(const std::string& key) const; - }; - - struct UploadFormData { - std::string name; - std::string content; - std::string filename; - std::string content_type; - }; - using UploadFormDataItems = std::vector; - - class DataSink { - public: - DataSink() : os(&sb_), sb_(*this) {} - - DataSink(const DataSink&) = delete; - DataSink& operator=(const DataSink&) = delete; - DataSink(DataSink&&) = delete; - DataSink& operator=(DataSink&&) = delete; - - std::function write; - std::function is_writable; - std::function done; - std::function done_with_trailer; - std::ostream os; - - private: - class data_sink_streambuf final : public std::streambuf { - public: - explicit data_sink_streambuf(DataSink& sink) : sink_(sink) {} - - protected: - std::streamsize xsputn(const char* s, std::streamsize n) override { - sink_.write(s, static_cast(n)); - return n; - } - - private: - DataSink& sink_; - }; - - data_sink_streambuf sb_; - }; - - using ContentProvider = std::function; - - using ContentProviderWithoutLength = std::function; - - using ContentProviderResourceReleaser = std::function; - - struct FormDataProvider { - std::string name; - ContentProviderWithoutLength provider; - std::string filename; - std::string content_type; - }; - using FormDataProviderItems = std::vector; - - using ContentReceiverWithProgress = std::function; - - using ContentReceiver = std::function; - - using FormDataHeader = std::function; - - class ContentReader { - public: - using Reader = std::function; - using FormDataReader = std::function; - - ContentReader(Reader reader, FormDataReader multipart_reader) - : reader_(std::move(reader)), formdata_reader_(std::move(multipart_reader)) {} - - bool operator()(FormDataHeader header, ContentReceiver receiver) const { - return formdata_reader_(std::move(header), std::move(receiver)); - } - - bool operator()(ContentReceiver receiver) const { return reader_(std::move(receiver)); } - - Reader reader_; - FormDataReader formdata_reader_; - }; - - using Range = std::pair; - using Ranges = std::vector; - - struct Request { - std::string method; - std::string path; - std::string matched_route; - Params params; - Headers headers; - Headers trailers; - std::string body; - - std::string remote_addr; - int remote_port = -1; - std::string local_addr; - int local_port = -1; - - // for server - std::string version; - std::string target; - MultipartFormData form; - Ranges ranges; - Match matches; - std::unordered_map path_params; - std::function is_connection_closed = []() { return true; }; - - // for client - std::vector accept_content_types; - ResponseHandler response_handler; - ContentReceiverWithProgress content_receiver; - DownloadProgress download_progress; - UploadProgress upload_progress; -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - const SSL* ssl = nullptr; -#endif - - bool has_header(const std::string& key) const; - std::string get_header_value(const std::string& key, const char* def = "", - size_t id = 0) const; - size_t get_header_value_u64(const std::string& key, size_t def = 0, size_t id = 0) const; - size_t get_header_value_count(const std::string& key) const; - void set_header(const std::string& key, const std::string& val); - - bool has_trailer(const std::string& key) const; - std::string get_trailer_value(const std::string& key, size_t id = 0) const; - size_t get_trailer_value_count(const std::string& key) const; - - bool has_param(const std::string& key) const; - std::string get_param_value(const std::string& key, size_t id = 0) const; - size_t get_param_value_count(const std::string& key) const; - - bool is_multipart_form_data() const; - - // private members... - size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT; - size_t content_length_ = 0; - ContentProvider content_provider_; - bool is_chunked_content_provider_ = false; - size_t authorization_count_ = 0; - std::chrono::time_point start_time_ = - (std::chrono::steady_clock::time_point::min)(); - }; - - struct Response { - std::string version; - int status = -1; - std::string reason; - Headers headers; - Headers trailers; - std::string body; - std::string location; // Redirect location - - bool has_header(const std::string& key) const; - std::string get_header_value(const std::string& key, const char* def = "", - size_t id = 0) const; - size_t get_header_value_u64(const std::string& key, size_t def = 0, size_t id = 0) const; - size_t get_header_value_count(const std::string& key) const; - void set_header(const std::string& key, const std::string& val); - - bool has_trailer(const std::string& key) const; - std::string get_trailer_value(const std::string& key, size_t id = 0) const; - size_t get_trailer_value_count(const std::string& key) const; - - void set_redirect(const std::string& url, int status = StatusCode::Found_302); - void set_content(const char* s, size_t n, const std::string& content_type); - void set_content(const std::string& s, const std::string& content_type); - void set_content(std::string&& s, const std::string& content_type); - - void set_content_provider(size_t length, const std::string& content_type, - ContentProvider provider, - ContentProviderResourceReleaser resource_releaser = nullptr); - - void set_content_provider(const std::string& content_type, - ContentProviderWithoutLength provider, - ContentProviderResourceReleaser resource_releaser = nullptr); - - void set_chunked_content_provider( - const std::string& content_type, ContentProviderWithoutLength provider, - ContentProviderResourceReleaser resource_releaser = nullptr); - - void set_file_content(const std::string& path, const std::string& content_type); - void set_file_content(const std::string& path); - - Response() = default; - Response(const Response&) = default; - Response& operator=(const Response&) = default; - Response(Response&&) = default; - Response& operator=(Response&&) = default; - ~Response() { - if (content_provider_resource_releaser_) { - content_provider_resource_releaser_(content_provider_success_); - } - } - - // private members... - size_t content_length_ = 0; - ContentProvider content_provider_; - ContentProviderResourceReleaser content_provider_resource_releaser_; - bool is_chunked_content_provider_ = false; - bool content_provider_success_ = false; - std::string file_content_path_; - std::string file_content_content_type_; - }; - - class Stream { - public: - virtual ~Stream() = default; - - virtual bool is_readable() const = 0; - virtual bool wait_readable() const = 0; - virtual bool wait_writable() const = 0; - - virtual ssize_t read(char* ptr, size_t size) = 0; - virtual ssize_t write(const char* ptr, size_t size) = 0; - virtual void get_remote_ip_and_port(std::string& ip, int& port) const = 0; - virtual void get_local_ip_and_port(std::string& ip, int& port) const = 0; - virtual socket_t socket() const = 0; - - virtual time_t duration() const = 0; - - ssize_t write(const char* ptr); - ssize_t write(const std::string& s); - }; - - class TaskQueue { - public: - TaskQueue() = default; - virtual ~TaskQueue() = default; - - virtual bool enqueue(std::function fn) = 0; - virtual void shutdown() = 0; - - virtual void on_idle() {} - }; - - class ThreadPool final : public TaskQueue { - public: - explicit ThreadPool(size_t n, size_t mqr = 0) - : shutdown_(false), max_queued_requests_(mqr) { - while (n) { - threads_.emplace_back(worker(*this)); - n--; - } - } - - ThreadPool(const ThreadPool&) = delete; - ~ThreadPool() override = default; - - bool enqueue(std::function fn) override { - { - std::unique_lock lock(mutex_); - if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) { - return false; - } - jobs_.push_back(std::move(fn)); - } - - cond_.notify_one(); - return true; - } - - void shutdown() override { - // Stop all worker threads... - { - std::unique_lock lock(mutex_); - shutdown_ = true; - } - - cond_.notify_all(); - - // Join... - for (auto& t : threads_) { - t.join(); - } - } - - private: - struct worker { - explicit worker(ThreadPool& pool) : pool_(pool) {} - - void operator()() { - for (;;) { - std::function fn; - { - std::unique_lock lock(pool_.mutex_); - - pool_.cond_.wait(lock, - [&] { return !pool_.jobs_.empty() || pool_.shutdown_; }); - - if (pool_.shutdown_ && pool_.jobs_.empty()) { - break; - } - - fn = pool_.jobs_.front(); - pool_.jobs_.pop_front(); - } - - assert(true == static_cast(fn)); - fn(); - } - -#if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \ - !defined(LIBRESSL_VERSION_NUMBER) - OPENSSL_thread_stop(); -#endif - } - - ThreadPool& pool_; - }; - friend struct worker; - - std::vector threads_; - std::list> jobs_; - - bool shutdown_; - size_t max_queued_requests_ = 0; - - std::condition_variable cond_; - std::mutex mutex_; - }; - - using Logger = std::function; - - // Forward declaration for Error type - enum class Error; - using ErrorLogger = std::function; - - using SocketOptions = std::function; - - namespace detail { - - bool set_socket_opt_impl(socket_t sock, int level, int optname, const void* optval, - socklen_t optlen); - bool set_socket_opt(socket_t sock, int level, int optname, int opt); - bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec, time_t usec); - - } // namespace detail - - void default_socket_options(socket_t sock); - - const char* status_message(int status); - - std::string get_bearer_token_auth(const Request& req); - - namespace detail { - - class MatcherBase { - public: - MatcherBase(std::string pattern) : pattern_(pattern) {} - virtual ~MatcherBase() = default; - - const std::string& pattern() const { return pattern_; } - - // Match request path and populate its matches and - virtual bool match(Request& request) const = 0; - - private: - std::string pattern_; - }; - - /** - * Captures parameters in request path and stores them in Request::path_params - * - * Capture name is a substring of a pattern from : to /. - * The rest of the pattern is matched against the request path directly - * Parameters are captured starting from the next character after - * the end of the last matched static pattern fragment until the next /. - * - * Example pattern: - * "/path/fragments/:capture/more/fragments/:second_capture" - * Static fragments: - * "/path/fragments/", "more/fragments/" - * - * Given the following request path: - * "/path/fragments/:1/more/fragments/:2" - * the resulting capture will be - * {{"capture", "1"}, {"second_capture", "2"}} - */ - class PathParamsMatcher final : public MatcherBase { - public: - PathParamsMatcher(const std::string& pattern); - - bool match(Request& request) const override; - - private: - // Treat segment separators as the end of path parameter capture - // Does not need to handle query parameters as they are parsed before path - // matching - static constexpr char separator = '/'; - - // Contains static path fragments to match against, excluding the '/' after - // path params - // Fragments are separated by path params - std::vector static_fragments_; - // Stores the names of the path parameters to be used as keys in the - // Request::path_params map - std::vector param_names_; - }; - - /** - * Performs std::regex_match on request path - * and stores the result in Request::matches - * - * Note that regex match is performed directly on the whole request. - * This means that wildcard patterns may match multiple path segments with /: - * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end". - */ - class RegexMatcher final : public MatcherBase { - public: - RegexMatcher(const std::string& pattern) : MatcherBase(pattern), regex_(pattern) {} - - bool match(Request& request) const override; - - private: - std::regex regex_; - }; - - ssize_t write_headers(Stream& strm, const Headers& headers); - - std::string make_host_and_port_string(const std::string& host, int port, bool is_ssl); - - } // namespace detail - - class Server { - public: - using Handler = std::function; - - using ExceptionHandler = - std::function; - - enum class HandlerResponse { - Handled, - Unhandled, - }; - using HandlerWithResponse = std::function; - - using HandlerWithContentReader = - std::function; - - using Expect100ContinueHandler = std::function; - - Server(); - - virtual ~Server(); - - virtual bool is_valid() const; - - Server& Get(const std::string& pattern, Handler handler); - Server& Post(const std::string& pattern, Handler handler); - Server& Post(const std::string& pattern, HandlerWithContentReader handler); - Server& Put(const std::string& pattern, Handler handler); - Server& Put(const std::string& pattern, HandlerWithContentReader handler); - Server& Patch(const std::string& pattern, Handler handler); - Server& Patch(const std::string& pattern, HandlerWithContentReader handler); - Server& Delete(const std::string& pattern, Handler handler); - Server& Delete(const std::string& pattern, HandlerWithContentReader handler); - Server& Options(const std::string& pattern, Handler handler); - - bool set_base_dir(const std::string& dir, const std::string& mount_point = std::string()); - bool set_mount_point(const std::string& mount_point, const std::string& dir, - Headers headers = Headers()); - bool remove_mount_point(const std::string& mount_point); - Server& set_file_extension_and_mimetype_mapping(const std::string& ext, - const std::string& mime); - Server& set_default_file_mimetype(const std::string& mime); - Server& set_file_request_handler(Handler handler); - - template - Server& set_error_handler(ErrorHandlerFunc&& handler) { - return set_error_handler_core( - std::forward(handler), - std::is_convertible{}); - } - - Server& set_exception_handler(ExceptionHandler handler); - - Server& set_pre_routing_handler(HandlerWithResponse handler); - Server& set_post_routing_handler(Handler handler); - - Server& set_pre_request_handler(HandlerWithResponse handler); - - Server& set_expect_100_continue_handler(Expect100ContinueHandler handler); - Server& set_logger(Logger logger); - Server& set_pre_compression_logger(Logger logger); - Server& set_error_logger(ErrorLogger error_logger); - - Server& set_address_family(int family); - Server& set_tcp_nodelay(bool on); - Server& set_ipv6_v6only(bool on); - Server& set_socket_options(SocketOptions socket_options); - - Server& set_default_headers(Headers headers); - Server& set_header_writer(std::function const& writer); - - Server& set_trusted_proxies(const std::vector& proxies); - - Server& set_keep_alive_max_count(size_t count); - Server& set_keep_alive_timeout(time_t sec); - - Server& set_read_timeout(time_t sec, time_t usec = 0); - template - Server& set_read_timeout(const std::chrono::duration& duration); - - Server& set_write_timeout(time_t sec, time_t usec = 0); - template - Server& set_write_timeout(const std::chrono::duration& duration); - - Server& set_idle_interval(time_t sec, time_t usec = 0); - template - Server& set_idle_interval(const std::chrono::duration& duration); - - Server& set_payload_max_length(size_t length); - - bool bind_to_port(const std::string& host, int port, int socket_flags = 0); - int bind_to_any_port(const std::string& host, int socket_flags = 0); - bool listen_after_bind(); - - bool listen(const std::string& host, int port, int socket_flags = 0); - - bool is_running() const; - void wait_until_ready() const; - void stop(); - void decommission(); - - std::function new_task_queue; - - protected: - bool process_request(Stream& strm, const std::string& remote_addr, int remote_port, - const std::string& local_addr, int local_port, bool close_connection, - bool& connection_closed, - const std::function& setup_request); - - std::atomic svr_sock_{INVALID_SOCKET}; - - std::vector trusted_proxies_; - - size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT; - time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND; - time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND; - time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND; - time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND; - time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND; - time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND; - time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND; - size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH; - - private: - using Handlers = std::vector, Handler>>; - using HandlersForContentReader = - std::vector, HandlerWithContentReader>>; - - static std::unique_ptr make_matcher(const std::string& pattern); - - Server& set_error_handler_core(HandlerWithResponse handler, std::true_type); - Server& set_error_handler_core(Handler handler, std::false_type); - - socket_t create_server_socket(const std::string& host, int port, int socket_flags, - SocketOptions socket_options) const; - int bind_internal(const std::string& host, int port, int socket_flags); - bool listen_internal(); - - bool routing(Request& req, Response& res, Stream& strm); - bool handle_file_request(const Request& req, Response& res); - bool dispatch_request(Request& req, Response& res, const Handlers& handlers) const; - bool dispatch_request_for_content_reader(Request& req, Response& res, - ContentReader content_reader, - const HandlersForContentReader& handlers) const; - - bool parse_request_line(const char* s, Request& req) const; - void apply_ranges(const Request& req, Response& res, std::string& content_type, - std::string& boundary) const; - bool write_response(Stream& strm, bool close_connection, Request& req, Response& res); - bool write_response_with_content(Stream& strm, bool close_connection, const Request& req, - Response& res); - bool write_response_core(Stream& strm, bool close_connection, const Request& req, - Response& res, bool need_apply_ranges); - bool write_content_with_provider(Stream& strm, const Request& req, Response& res, - const std::string& boundary, - const std::string& content_type); - bool read_content(Stream& strm, Request& req, Response& res); - bool read_content_with_content_receiver(Stream& strm, Request& req, Response& res, - ContentReceiver receiver, - FormDataHeader multipart_header, - ContentReceiver multipart_receiver); - bool read_content_core(Stream& strm, Request& req, Response& res, ContentReceiver receiver, - FormDataHeader multipart_header, - ContentReceiver multipart_receiver) const; - - virtual bool process_and_close_socket(socket_t sock); - - void output_log(const Request& req, const Response& res) const; - void output_pre_compression_log(const Request& req, const Response& res) const; - void output_error_log(const Error& err, const Request* req) const; - - std::atomic is_running_{false}; - std::atomic is_decommissioned{false}; - - struct MountPointEntry { - std::string mount_point; - std::string base_dir; - Headers headers; - }; - std::vector base_dirs_; - std::map file_extension_and_mimetype_map_; - std::string default_file_mimetype_ = "application/octet-stream"; - Handler file_request_handler_; - - Handlers get_handlers_; - Handlers post_handlers_; - HandlersForContentReader post_handlers_for_content_reader_; - Handlers put_handlers_; - HandlersForContentReader put_handlers_for_content_reader_; - Handlers patch_handlers_; - HandlersForContentReader patch_handlers_for_content_reader_; - Handlers delete_handlers_; - HandlersForContentReader delete_handlers_for_content_reader_; - Handlers options_handlers_; - - HandlerWithResponse error_handler_; - ExceptionHandler exception_handler_; - HandlerWithResponse pre_routing_handler_; - Handler post_routing_handler_; - HandlerWithResponse pre_request_handler_; - Expect100ContinueHandler expect_100_continue_handler_; - - mutable std::mutex logger_mutex_; - Logger logger_; - Logger pre_compression_logger_; - ErrorLogger error_logger_; - - int address_family_ = AF_UNSPEC; - bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY; - bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY; - SocketOptions socket_options_ = default_socket_options; - - Headers default_headers_; - std::function header_writer_ = detail::write_headers; - }; - - enum class Error { - Success = 0, - Unknown, - Connection, - BindIPAddress, - Read, - Write, - ExceedRedirectCount, - Canceled, - SSLConnection, - SSLLoadingCerts, - SSLServerVerification, - SSLServerHostnameVerification, - UnsupportedMultipartBoundaryChars, - Compression, - ConnectionTimeout, - ProxyConnection, - ResourceExhaustion, - TooManyFormDataFiles, - ExceedMaxPayloadSize, - ExceedUriMaxLength, - ExceedMaxSocketDescriptorCount, - InvalidRequestLine, - InvalidHTTPMethod, - InvalidHTTPVersion, - InvalidHeaders, - MultipartParsing, - OpenFile, - Listen, - GetSockName, - UnsupportedAddressFamily, - HTTPParsing, - InvalidRangeHeader, - - // For internal use only - SSLPeerCouldBeClosed_, - }; - - std::string to_string(Error error); - - std::ostream& operator<<(std::ostream& os, const Error& obj); - - class Result { - public: - Result() = default; - Result(std::unique_ptr&& res, Error err, Headers&& request_headers = Headers{}) - : res_(std::move(res)), err_(err), request_headers_(std::move(request_headers)) {} -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - Result(std::unique_ptr&& res, Error err, Headers&& request_headers, int ssl_error) - : res_(std::move(res)), - err_(err), - request_headers_(std::move(request_headers)), - ssl_error_(ssl_error) {} - Result(std::unique_ptr&& res, Error err, Headers&& request_headers, int ssl_error, - unsigned long ssl_openssl_error) - : res_(std::move(res)), - err_(err), - request_headers_(std::move(request_headers)), - ssl_error_(ssl_error), - ssl_openssl_error_(ssl_openssl_error) {} -#endif - // Response - operator bool() const { return res_ != nullptr; } - bool operator==(std::nullptr_t) const { return res_ == nullptr; } - bool operator!=(std::nullptr_t) const { return res_ != nullptr; } - const Response& value() const { return *res_; } - Response& value() { return *res_; } - const Response& operator*() const { return *res_; } - Response& operator*() { return *res_; } - const Response* operator->() const { return res_.get(); } - Response* operator->() { return res_.get(); } - - // Error - Error error() const { return err_; } - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - // SSL Error - int ssl_error() const { return ssl_error_; } - // OpenSSL Error - unsigned long ssl_openssl_error() const { return ssl_openssl_error_; } -#endif - - // Request Headers - bool has_request_header(const std::string& key) const; - std::string get_request_header_value(const std::string& key, const char* def = "", - size_t id = 0) const; - size_t get_request_header_value_u64(const std::string& key, size_t def = 0, - size_t id = 0) const; - size_t get_request_header_value_count(const std::string& key) const; - - private: - std::unique_ptr res_; - Error err_ = Error::Unknown; - Headers request_headers_; -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - int ssl_error_ = 0; - unsigned long ssl_openssl_error_ = 0; -#endif - }; - - class ClientImpl { - public: - explicit ClientImpl(const std::string& host); - - explicit ClientImpl(const std::string& host, int port); - - explicit ClientImpl(const std::string& host, int port, const std::string& client_cert_path, - const std::string& client_key_path); - - virtual ~ClientImpl(); - - virtual bool is_valid() const; - - // clang-format off - Result Get(const std::string &path, DownloadProgress progress = nullptr); - Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr); - Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - Result Get(const std::string &path, const Params ¶ms, const Headers &headers, DownloadProgress progress = nullptr); - Result Get(const std::string &path, const Params ¶ms, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - Result Get(const std::string &path, const Params ¶ms, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - - Result Head(const std::string &path); - Result Head(const std::string &path, const Headers &headers); - - Result Post(const std::string &path); - Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr); - Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr); - Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Post(const std::string &path, const Params ¶ms); - Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers); - Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers, const Params ¶ms); - Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - - Result Put(const std::string &path); - Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr); - Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr); - Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Params ¶ms); - Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers); - Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers, const Params ¶ms); - Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - - Result Patch(const std::string &path); - Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr); - Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Params ¶ms); - Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, const Params ¶ms); - Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - - Result Delete(const std::string &path, DownloadProgress progress = nullptr); - Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr); - Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr); - Result Delete(const std::string &path, const Params ¶ms, DownloadProgress progress = nullptr); - Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr); - Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr); - Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr); - Result Delete(const std::string &path, const Headers &headers, const Params ¶ms, DownloadProgress progress = nullptr); - - Result Options(const std::string &path); - Result Options(const std::string &path, const Headers &headers); - // clang-format on - - bool send(Request& req, Response& res, Error& error); - Result send(const Request& req); - - void stop(); - - std::string host() const; - int port() const; - - size_t is_socket_open() const; - socket_t socket() const; - - void set_hostname_addr_map(std::map addr_map); - - void set_default_headers(Headers headers); - - void set_header_writer(std::function const& writer); - - void set_address_family(int family); - void set_tcp_nodelay(bool on); - void set_ipv6_v6only(bool on); - void set_socket_options(SocketOptions socket_options); - - void set_connection_timeout(time_t sec, time_t usec = 0); - template - void set_connection_timeout(const std::chrono::duration& duration); - - void set_read_timeout(time_t sec, time_t usec = 0); - template - void set_read_timeout(const std::chrono::duration& duration); - - void set_write_timeout(time_t sec, time_t usec = 0); - template - void set_write_timeout(const std::chrono::duration& duration); - - void set_max_timeout(time_t msec); - template - void set_max_timeout(const std::chrono::duration& duration); - - void set_basic_auth(const std::string& username, const std::string& password); - void set_bearer_token_auth(const std::string& token); -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - void set_digest_auth(const std::string& username, const std::string& password); -#endif - - void set_keep_alive(bool on); - void set_follow_location(bool on); - - void set_path_encode(bool on); - - void set_compress(bool on); - - void set_decompress(bool on); - - void set_interface(const std::string& intf); - - void set_proxy(const std::string& host, int port); - void set_proxy_basic_auth(const std::string& username, const std::string& password); - void set_proxy_bearer_token_auth(const std::string& token); -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - void set_proxy_digest_auth(const std::string& username, const std::string& password); -#endif - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - void set_ca_cert_path(const std::string& ca_cert_file_path, - const std::string& ca_cert_dir_path = std::string()); - void set_ca_cert_store(X509_STORE* ca_cert_store); - X509_STORE* create_ca_cert_store(const char* ca_cert, std::size_t size) const; -#endif - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - void enable_server_certificate_verification(bool enabled); - void enable_server_hostname_verification(bool enabled); - void set_server_certificate_verifier(std::function verifier); -#endif - - void set_logger(Logger logger); - void set_error_logger(ErrorLogger error_logger); - - protected: - struct Socket { - socket_t sock = INVALID_SOCKET; -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - SSL* ssl = nullptr; -#endif - - bool is_open() const { return sock != INVALID_SOCKET; } - }; - - virtual bool create_and_connect_socket(Socket& socket, Error& error); - - // All of: - // shutdown_ssl - // shutdown_socket - // close_socket - // should ONLY be called when socket_mutex_ is locked. - // Also, shutdown_ssl and close_socket should also NOT be called concurrently - // with a DIFFERENT thread sending requests using that socket. - virtual void shutdown_ssl(Socket& socket, bool shutdown_gracefully); - void shutdown_socket(Socket& socket) const; - void close_socket(Socket& socket); - - bool process_request(Stream& strm, Request& req, Response& res, bool close_connection, - Error& error); - - bool write_content_with_provider(Stream& strm, const Request& req, Error& error) const; - - void copy_settings(const ClientImpl& rhs); - - void output_log(const Request& req, const Response& res) const; - void output_error_log(const Error& err, const Request* req) const; - - // Socket endpoint information - const std::string host_; - const int port_; - const std::string host_and_port_; - - // Current open socket - Socket socket_; - mutable std::mutex socket_mutex_; - std::recursive_mutex request_mutex_; - - // These are all protected under socket_mutex - size_t socket_requests_in_flight_ = 0; - std::thread::id socket_requests_are_from_thread_ = std::thread::id(); - bool socket_should_be_closed_when_request_is_done_ = false; - - // Hostname-IP map - std::map addr_map_; - - // Default headers - Headers default_headers_; - - // Header writer - std::function header_writer_ = detail::write_headers; - - // Settings - std::string client_cert_path_; - std::string client_key_path_; - - time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND; - time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND; - time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND; - time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND; - time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND; - time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND; - time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND; - - std::string basic_auth_username_; - std::string basic_auth_password_; - std::string bearer_token_auth_token_; -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - std::string digest_auth_username_; - std::string digest_auth_password_; -#endif - - bool keep_alive_ = false; - bool follow_location_ = false; - - bool path_encode_ = true; - - int address_family_ = AF_UNSPEC; - bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY; - bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY; - SocketOptions socket_options_ = nullptr; - - bool compress_ = false; - bool decompress_ = true; - - std::string interface_; - - std::string proxy_host_; - int proxy_port_ = -1; - - std::string proxy_basic_auth_username_; - std::string proxy_basic_auth_password_; - std::string proxy_bearer_token_auth_token_; -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - std::string proxy_digest_auth_username_; - std::string proxy_digest_auth_password_; -#endif - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - std::string ca_cert_file_path_; - std::string ca_cert_dir_path_; - - X509_STORE* ca_cert_store_ = nullptr; -#endif - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - bool server_certificate_verification_ = true; - bool server_hostname_verification_ = true; - std::function server_certificate_verifier_; -#endif - - mutable std::mutex logger_mutex_; - Logger logger_; - ErrorLogger error_logger_; - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - int last_ssl_error_ = 0; - unsigned long last_openssl_error_ = 0; -#endif - - private: - bool send_(Request& req, Response& res, Error& error); - Result send_(Request&& req); - - socket_t create_client_socket(Error& error) const; - bool read_response_line(Stream& strm, const Request& req, Response& res) const; - bool write_request(Stream& strm, Request& req, bool close_connection, Error& error); - bool redirect(Request& req, Response& res, Error& error); - bool create_redirect_client(const std::string& scheme, const std::string& host, int port, - Request& req, Response& res, const std::string& path, - const std::string& location, Error& error); - template - void setup_redirect_client(ClientType& client); - bool handle_request(Stream& strm, Request& req, Response& res, bool close_connection, - Error& error); - std::unique_ptr send_with_content_provider_and_receiver( - Request& req, const char* body, size_t content_length, ContentProvider content_provider, - ContentProviderWithoutLength content_provider_without_length, - const std::string& content_type, ContentReceiver content_receiver, Error& error); - Result send_with_content_provider_and_receiver( - const std::string& method, const std::string& path, const Headers& headers, - const char* body, size_t content_length, ContentProvider content_provider, - ContentProviderWithoutLength content_provider_without_length, - const std::string& content_type, ContentReceiver content_receiver, - UploadProgress progress); - ContentProviderWithoutLength get_multipart_content_provider( - const std::string& boundary, const UploadFormDataItems& items, - const FormDataProviderItems& provider_items) const; - - virtual bool process_socket(const Socket& socket, - std::chrono::time_point start_time, - std::function callback); - virtual bool is_ssl() const; - }; - - class Client { - public: - // Universal interface - explicit Client(const std::string& scheme_host_port); - - explicit Client(const std::string& scheme_host_port, const std::string& client_cert_path, - const std::string& client_key_path); - - // HTTP only interface - explicit Client(const std::string& host, int port); - - explicit Client(const std::string& host, int port, const std::string& client_cert_path, - const std::string& client_key_path); - - Client(Client&&) = default; - Client& operator=(Client&&) = default; - - ~Client(); - - bool is_valid() const; - - // clang-format off - Result Get(const std::string &path, DownloadProgress progress = nullptr); - Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr); - Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - Result Get(const std::string &path, const Params ¶ms, const Headers &headers, DownloadProgress progress = nullptr); - Result Get(const std::string &path, const Params ¶ms, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - Result Get(const std::string &path, const Params ¶ms, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - - Result Head(const std::string &path); - Result Head(const std::string &path, const Headers &headers); - - Result Post(const std::string &path); - Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr); - Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr); - Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Post(const std::string &path, const Params ¶ms); - Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers); - Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers, const Params ¶ms); - Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr); - Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - - Result Put(const std::string &path); - Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr); - Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr); - Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Params ¶ms); - Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers); - Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers, const Params ¶ms); - Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr); - Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - - Result Patch(const std::string &path); - Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr); - Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Params ¶ms); - Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers); - Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, const Params ¶ms); - Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr); - Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr); - - Result Delete(const std::string &path, DownloadProgress progress = nullptr); - Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr); - Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr); - Result Delete(const std::string &path, const Params ¶ms, DownloadProgress progress = nullptr); - Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr); - Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr); - Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr); - Result Delete(const std::string &path, const Headers &headers, const Params ¶ms, DownloadProgress progress = nullptr); - - Result Options(const std::string &path); - Result Options(const std::string &path, const Headers &headers); - // clang-format on - - bool send(Request& req, Response& res, Error& error); - Result send(const Request& req); - - void stop(); - - std::string host() const; - int port() const; - - size_t is_socket_open() const; - socket_t socket() const; - - void set_hostname_addr_map(std::map addr_map); - - void set_default_headers(Headers headers); - - void set_header_writer(std::function const& writer); - - void set_address_family(int family); - void set_tcp_nodelay(bool on); - void set_socket_options(SocketOptions socket_options); - - void set_connection_timeout(time_t sec, time_t usec = 0); - template - void set_connection_timeout(const std::chrono::duration& duration); - - void set_read_timeout(time_t sec, time_t usec = 0); - template - void set_read_timeout(const std::chrono::duration& duration); - - void set_write_timeout(time_t sec, time_t usec = 0); - template - void set_write_timeout(const std::chrono::duration& duration); - - void set_max_timeout(time_t msec); - template - void set_max_timeout(const std::chrono::duration& duration); - - void set_basic_auth(const std::string& username, const std::string& password); - void set_bearer_token_auth(const std::string& token); -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - void set_digest_auth(const std::string& username, const std::string& password); -#endif - - void set_keep_alive(bool on); - void set_follow_location(bool on); - - void set_path_encode(bool on); - void set_url_encode(bool on); - - void set_compress(bool on); - - void set_decompress(bool on); - - void set_interface(const std::string& intf); - - void set_proxy(const std::string& host, int port); - void set_proxy_basic_auth(const std::string& username, const std::string& password); - void set_proxy_bearer_token_auth(const std::string& token); -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - void set_proxy_digest_auth(const std::string& username, const std::string& password); -#endif - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - void enable_server_certificate_verification(bool enabled); - void enable_server_hostname_verification(bool enabled); - void set_server_certificate_verifier(std::function verifier); -#endif - - void set_logger(Logger logger); - void set_error_logger(ErrorLogger error_logger); - - // SSL -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - void set_ca_cert_path(const std::string& ca_cert_file_path, - const std::string& ca_cert_dir_path = std::string()); - - void set_ca_cert_store(X509_STORE* ca_cert_store); - void load_ca_cert_store(const char* ca_cert, std::size_t size); - - long get_openssl_verify_result() const; - - SSL_CTX* ssl_context() const; -#endif - - private: - std::unique_ptr cli_; - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - bool is_ssl_ = false; -#endif - }; - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - class SSLServer : public Server { - public: - SSLServer(const char* cert_path, const char* private_key_path, - const char* client_ca_cert_file_path = nullptr, - const char* client_ca_cert_dir_path = nullptr, - const char* private_key_password = nullptr); - - SSLServer(X509* cert, EVP_PKEY* private_key, X509_STORE* client_ca_cert_store = nullptr); - - SSLServer(const std::function& setup_ssl_ctx_callback); - - ~SSLServer() override; - - bool is_valid() const override; - - SSL_CTX* ssl_context() const; - - void update_certs(X509* cert, EVP_PKEY* private_key, - X509_STORE* client_ca_cert_store = nullptr); - - int ssl_last_error() const { return last_ssl_error_; } - - private: - bool process_and_close_socket(socket_t sock) override; - - STACK_OF(X509_NAME) * extract_ca_names_from_x509_store(X509_STORE* store); - - SSL_CTX* ctx_; - std::mutex ctx_mutex_; - - int last_ssl_error_ = 0; - }; - - class SSLClient final : public ClientImpl { - public: - explicit SSLClient(const std::string& host); - - explicit SSLClient(const std::string& host, int port); - - explicit SSLClient(const std::string& host, int port, const std::string& client_cert_path, - const std::string& client_key_path, - const std::string& private_key_password = std::string()); - - explicit SSLClient(const std::string& host, int port, X509* client_cert, - EVP_PKEY* client_key, - const std::string& private_key_password = std::string()); - - ~SSLClient() override; - - bool is_valid() const override; - - void set_ca_cert_store(X509_STORE* ca_cert_store); - void load_ca_cert_store(const char* ca_cert, std::size_t size); - - long get_openssl_verify_result() const; - - SSL_CTX* ssl_context() const; - - private: - bool create_and_connect_socket(Socket& socket, Error& error) override; - void shutdown_ssl(Socket& socket, bool shutdown_gracefully) override; - void shutdown_ssl_impl(Socket& socket, bool shutdown_gracefully); - - bool process_socket(const Socket& socket, - std::chrono::time_point start_time, - std::function callback) override; - bool is_ssl() const override; - - bool connect_with_proxy(Socket& sock, - std::chrono::time_point start_time, - Response& res, bool& success, Error& error); - bool initialize_ssl(Socket& socket, Error& error); - - bool load_certs(); - - bool verify_host(X509* server_cert) const; - bool verify_host_with_subject_alt_name(X509* server_cert) const; - bool verify_host_with_common_name(X509* server_cert) const; - bool check_host_name(const char* pattern, size_t pattern_len) const; - - SSL_CTX* ctx_; - std::mutex ctx_mutex_; - std::once_flag initialize_cert_; - - std::vector host_components_; - - long verify_result_ = 0; - - friend class ClientImpl; - }; -#endif - - /* - * Implementation of template methods. - */ - - namespace detail { - - template - inline void duration_to_sec_and_usec(const T& duration, U callback) { - auto sec = std::chrono::duration_cast(duration).count(); - auto usec = std::chrono::duration_cast( - duration - std::chrono::seconds(sec)) - .count(); - callback(static_cast(sec), static_cast(usec)); - } - - template - inline constexpr size_t str_len(const char (&)[N]) { - return N - 1; - } - - inline bool is_numeric(const std::string& str) { - return !str.empty() && std::all_of(str.cbegin(), str.cend(), - [](unsigned char c) { return std::isdigit(c); }); - } - - inline size_t get_header_value_u64(const Headers& headers, const std::string& key, - size_t def, size_t id, bool& is_invalid_value) { - is_invalid_value = false; - auto rng = headers.equal_range(key); - auto it = rng.first; - std::advance(it, static_cast(id)); - if (it != rng.second) { - if (is_numeric(it->second)) { - return std::strtoull(it->second.data(), nullptr, 10); - } else { - is_invalid_value = true; - } - } - return def; - } - - inline size_t get_header_value_u64(const Headers& headers, const std::string& key, - size_t def, size_t id) { - auto dummy = false; - return get_header_value_u64(headers, key, def, id, dummy); - } - - } // namespace detail - - inline size_t Request::get_header_value_u64(const std::string& key, size_t def, - size_t id) const { - return detail::get_header_value_u64(headers, key, def, id); - } - - inline size_t Response::get_header_value_u64(const std::string& key, size_t def, - size_t id) const { - return detail::get_header_value_u64(headers, key, def, id); - } - - namespace detail { - - inline bool set_socket_opt_impl(socket_t sock, int level, int optname, const void* optval, - socklen_t optlen) { - return setsockopt(sock, level, optname, -#ifdef _WIN32 - reinterpret_cast(optval), -#else - optval, -#endif - optlen) == 0; - } - - inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) { - return set_socket_opt_impl(sock, level, optname, &optval, sizeof(optval)); - } - - inline bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec, - time_t usec) { -#ifdef _WIN32 - auto timeout = static_cast(sec * 1000 + usec / 1000); -#else - timeval timeout; - timeout.tv_sec = static_cast(sec); - timeout.tv_usec = static_cast(usec); -#endif - return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout)); - } - - } // namespace detail - - inline void default_socket_options(socket_t sock) { - detail::set_socket_opt(sock, SOL_SOCKET, -#ifdef SO_REUSEPORT - SO_REUSEPORT, -#else - SO_REUSEADDR, -#endif - 1); - } - - inline const char* status_message(int status) { - switch (status) { - case StatusCode::Continue_100: - return "Continue"; - case StatusCode::SwitchingProtocol_101: - return "Switching Protocol"; - case StatusCode::Processing_102: - return "Processing"; - case StatusCode::EarlyHints_103: - return "Early Hints"; - case StatusCode::OK_200: - return "OK"; - case StatusCode::Created_201: - return "Created"; - case StatusCode::Accepted_202: - return "Accepted"; - case StatusCode::NonAuthoritativeInformation_203: - return "Non-Authoritative Information"; - case StatusCode::NoContent_204: - return "No Content"; - case StatusCode::ResetContent_205: - return "Reset Content"; - case StatusCode::PartialContent_206: - return "Partial Content"; - case StatusCode::MultiStatus_207: - return "Multi-Status"; - case StatusCode::AlreadyReported_208: - return "Already Reported"; - case StatusCode::IMUsed_226: - return "IM Used"; - case StatusCode::MultipleChoices_300: - return "Multiple Choices"; - case StatusCode::MovedPermanently_301: - return "Moved Permanently"; - case StatusCode::Found_302: - return "Found"; - case StatusCode::SeeOther_303: - return "See Other"; - case StatusCode::NotModified_304: - return "Not Modified"; - case StatusCode::UseProxy_305: - return "Use Proxy"; - case StatusCode::unused_306: - return "unused"; - case StatusCode::TemporaryRedirect_307: - return "Temporary Redirect"; - case StatusCode::PermanentRedirect_308: - return "Permanent Redirect"; - case StatusCode::BadRequest_400: - return "Bad Request"; - case StatusCode::Unauthorized_401: - return "Unauthorized"; - case StatusCode::PaymentRequired_402: - return "Payment Required"; - case StatusCode::Forbidden_403: - return "Forbidden"; - case StatusCode::NotFound_404: - return "Not Found"; - case StatusCode::MethodNotAllowed_405: - return "Method Not Allowed"; - case StatusCode::NotAcceptable_406: - return "Not Acceptable"; - case StatusCode::ProxyAuthenticationRequired_407: - return "Proxy Authentication Required"; - case StatusCode::RequestTimeout_408: - return "Request Timeout"; - case StatusCode::Conflict_409: - return "Conflict"; - case StatusCode::Gone_410: - return "Gone"; - case StatusCode::LengthRequired_411: - return "Length Required"; - case StatusCode::PreconditionFailed_412: - return "Precondition Failed"; - case StatusCode::PayloadTooLarge_413: - return "Payload Too Large"; - case StatusCode::UriTooLong_414: - return "URI Too Long"; - case StatusCode::UnsupportedMediaType_415: - return "Unsupported Media Type"; - case StatusCode::RangeNotSatisfiable_416: - return "Range Not Satisfiable"; - case StatusCode::ExpectationFailed_417: - return "Expectation Failed"; - case StatusCode::ImATeapot_418: - return "I'm a teapot"; - case StatusCode::MisdirectedRequest_421: - return "Misdirected Request"; - case StatusCode::UnprocessableContent_422: - return "Unprocessable Content"; - case StatusCode::Locked_423: - return "Locked"; - case StatusCode::FailedDependency_424: - return "Failed Dependency"; - case StatusCode::TooEarly_425: - return "Too Early"; - case StatusCode::UpgradeRequired_426: - return "Upgrade Required"; - case StatusCode::PreconditionRequired_428: - return "Precondition Required"; - case StatusCode::TooManyRequests_429: - return "Too Many Requests"; - case StatusCode::RequestHeaderFieldsTooLarge_431: - return "Request Header Fields Too Large"; - case StatusCode::UnavailableForLegalReasons_451: - return "Unavailable For Legal Reasons"; - case StatusCode::NotImplemented_501: - return "Not Implemented"; - case StatusCode::BadGateway_502: - return "Bad Gateway"; - case StatusCode::ServiceUnavailable_503: - return "Service Unavailable"; - case StatusCode::GatewayTimeout_504: - return "Gateway Timeout"; - case StatusCode::HttpVersionNotSupported_505: - return "HTTP Version Not Supported"; - case StatusCode::VariantAlsoNegotiates_506: - return "Variant Also Negotiates"; - case StatusCode::InsufficientStorage_507: - return "Insufficient Storage"; - case StatusCode::LoopDetected_508: - return "Loop Detected"; - case StatusCode::NotExtended_510: - return "Not Extended"; - case StatusCode::NetworkAuthenticationRequired_511: - return "Network Authentication Required"; - - default: - case StatusCode::InternalServerError_500: - return "Internal Server Error"; - } - } - - inline std::string get_bearer_token_auth(const Request& req) { - if (req.has_header("Authorization")) { - constexpr auto bearer_header_prefix_len = detail::str_len("Bearer "); - return req.get_header_value("Authorization").substr(bearer_header_prefix_len); - } - return ""; - } - - template - inline Server& Server::set_read_timeout(const std::chrono::duration& duration) { - detail::duration_to_sec_and_usec( - duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); }); - return *this; - } - - template - inline Server& Server::set_write_timeout(const std::chrono::duration& duration) { - detail::duration_to_sec_and_usec( - duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); }); - return *this; - } - - template - inline Server& Server::set_idle_interval(const std::chrono::duration& duration) { - detail::duration_to_sec_and_usec( - duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); }); - return *this; - } - - inline std::string to_string(const Error error) { - switch (error) { - case Error::Success: - return "Success (no error)"; - case Error::Unknown: - return "Unknown"; - case Error::Connection: - return "Could not establish connection"; - case Error::BindIPAddress: - return "Failed to bind IP address"; - case Error::Read: - return "Failed to read connection"; - case Error::Write: - return "Failed to write connection"; - case Error::ExceedRedirectCount: - return "Maximum redirect count exceeded"; - case Error::Canceled: - return "Connection handling canceled"; - case Error::SSLConnection: - return "SSL connection failed"; - case Error::SSLLoadingCerts: - return "SSL certificate loading failed"; - case Error::SSLServerVerification: - return "SSL server verification failed"; - case Error::SSLServerHostnameVerification: - return "SSL server hostname verification failed"; - case Error::UnsupportedMultipartBoundaryChars: - return "Unsupported HTTP multipart boundary characters"; - case Error::Compression: - return "Compression failed"; - case Error::ConnectionTimeout: - return "Connection timed out"; - case Error::ProxyConnection: - return "Proxy connection failed"; - case Error::ResourceExhaustion: - return "Resource exhaustion"; - case Error::TooManyFormDataFiles: - return "Too many form data files"; - case Error::ExceedMaxPayloadSize: - return "Exceeded maximum payload size"; - case Error::ExceedUriMaxLength: - return "Exceeded maximum URI length"; - case Error::ExceedMaxSocketDescriptorCount: - return "Exceeded maximum socket descriptor count"; - case Error::InvalidRequestLine: - return "Invalid request line"; - case Error::InvalidHTTPMethod: - return "Invalid HTTP method"; - case Error::InvalidHTTPVersion: - return "Invalid HTTP version"; - case Error::InvalidHeaders: - return "Invalid headers"; - case Error::MultipartParsing: - return "Multipart parsing failed"; - case Error::OpenFile: - return "Failed to open file"; - case Error::Listen: - return "Failed to listen on socket"; - case Error::GetSockName: - return "Failed to get socket name"; - case Error::UnsupportedAddressFamily: - return "Unsupported address family"; - case Error::HTTPParsing: - return "HTTP parsing failed"; - case Error::InvalidRangeHeader: - return "Invalid Range header"; - default: - break; - } - - return "Invalid"; - } - - inline std::ostream& operator<<(std::ostream& os, const Error& obj) { - os << to_string(obj); - os << " (" << static_cast::type>(obj) << ')'; - return os; - } - - inline size_t Result::get_request_header_value_u64(const std::string& key, size_t def, - size_t id) const { - return detail::get_header_value_u64(request_headers_, key, def, id); - } - - template - inline void ClientImpl::set_connection_timeout( - const std::chrono::duration& duration) { - detail::duration_to_sec_and_usec( - duration, [&](time_t sec, time_t usec) { set_connection_timeout(sec, usec); }); - } - - template - inline void ClientImpl::set_read_timeout(const std::chrono::duration& duration) { - detail::duration_to_sec_and_usec( - duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); }); - } - - template - inline void ClientImpl::set_write_timeout(const std::chrono::duration& duration) { - detail::duration_to_sec_and_usec( - duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); }); - } - - template - inline void ClientImpl::set_max_timeout(const std::chrono::duration& duration) { - auto msec = std::chrono::duration_cast(duration).count(); - set_max_timeout(msec); - } - - template - inline void Client::set_connection_timeout(const std::chrono::duration& duration) { - cli_->set_connection_timeout(duration); - } - - template - inline void Client::set_read_timeout(const std::chrono::duration& duration) { - cli_->set_read_timeout(duration); - } - - template - inline void Client::set_write_timeout(const std::chrono::duration& duration) { - cli_->set_write_timeout(duration); - } - - inline void Client::set_max_timeout(time_t msec) { cli_->set_max_timeout(msec); } - - template - inline void Client::set_max_timeout(const std::chrono::duration& duration) { - cli_->set_max_timeout(duration); - } - - /* - * Forward declarations and types that will be part of the .h file if split into - * .h + .cc. - */ - - std::string hosted_at(const std::string& hostname); - - void hosted_at(const std::string& hostname, std::vector& addrs); - - // JavaScript-style URL encoding/decoding functions - std::string encode_uri_component(const std::string& value); - std::string encode_uri(const std::string& value); - std::string decode_uri_component(const std::string& value); - std::string decode_uri(const std::string& value); - - // RFC 3986 compliant URL component encoding/decoding functions - std::string encode_path_component(const std::string& component); - std::string decode_path_component(const std::string& component); - std::string encode_query_component(const std::string& component, bool space_as_plus = true); - std::string decode_query_component(const std::string& component, bool plus_as_space = true); - - std::string append_query_params(const std::string& path, const Params& params); - - std::pair make_range_header(const Ranges& ranges); - - std::pair make_basic_authentication_header( - const std::string& username, const std::string& password, bool is_proxy = false); - - namespace detail { - -#if defined(_WIN32) - inline std::wstring u8string_to_wstring(const char* s) { - std::wstring ws; - auto len = static_cast(strlen(s)); - auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0); - if (wlen > 0) { - ws.resize(wlen); - wlen = ::MultiByteToWideChar( - CP_UTF8, 0, s, len, const_cast(reinterpret_cast(ws.data())), - wlen); - if (wlen != static_cast(ws.size())) { - ws.clear(); - } - } - return ws; - } -#endif - - struct FileStat { - FileStat(const std::string& path); - bool is_file() const; - bool is_dir() const; - - private: -#if defined(_WIN32) - struct _stat st_; -#else - struct stat st_; -#endif - int ret_ = -1; - }; - - std::string trim_copy(const std::string& s); - - void divide(const char* data, std::size_t size, char d, - std::function fn); - - void divide(const std::string& str, char d, - std::function fn); - - void split(const char* b, const char* e, char d, - std::function fn); - - void split(const char* b, const char* e, char d, size_t m, - std::function fn); - - bool process_client_socket(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec, - time_t write_timeout_sec, time_t write_timeout_usec, - time_t max_timeout_msec, - std::chrono::time_point start_time, - std::function callback); - - socket_t create_client_socket(const std::string& host, const std::string& ip, int port, - int address_family, bool tcp_nodelay, bool ipv6_v6only, - SocketOptions socket_options, time_t connection_timeout_sec, - time_t connection_timeout_usec, time_t read_timeout_sec, - time_t read_timeout_usec, time_t write_timeout_sec, - time_t write_timeout_usec, const std::string& intf, - Error& error); - - const char* get_header_value(const Headers& headers, const std::string& key, - const char* def, size_t id); - - std::string params_to_query_str(const Params& params); - - void parse_query_text(const char* data, std::size_t size, Params& params); - - void parse_query_text(const std::string& s, Params& params); - - bool parse_multipart_boundary(const std::string& content_type, std::string& boundary); - - bool parse_range_header(const std::string& s, Ranges& ranges); - - bool parse_accept_header(const std::string& s, std::vector& content_types); - - int close_socket(socket_t sock); - - ssize_t send_socket(socket_t sock, const void* ptr, size_t size, int flags); - - ssize_t read_socket(socket_t sock, void* ptr, size_t size, int flags); - - enum class EncodingType { None = 0, Gzip, Brotli, Zstd }; - - EncodingType encoding_type(const Request& req, const Response& res); - - class BufferStream final : public Stream { - public: - BufferStream() = default; - ~BufferStream() override = default; - - bool is_readable() const override; - bool wait_readable() const override; - bool wait_writable() const override; - ssize_t read(char* ptr, size_t size) override; - ssize_t write(const char* ptr, size_t size) override; - void get_remote_ip_and_port(std::string& ip, int& port) const override; - void get_local_ip_and_port(std::string& ip, int& port) const override; - socket_t socket() const override; - time_t duration() const override; - - const std::string& get_buffer() const; - - private: - std::string buffer; - size_t position = 0; - }; - - class compressor { - public: - virtual ~compressor() = default; - - typedef std::function Callback; - virtual bool compress(const char* data, size_t data_length, bool last, - Callback callback) = 0; - }; - - class decompressor { - public: - virtual ~decompressor() = default; - - virtual bool is_valid() const = 0; - - typedef std::function Callback; - virtual bool decompress(const char* data, size_t data_length, Callback callback) = 0; - }; - - class nocompressor final : public compressor { - public: - ~nocompressor() override = default; - - bool compress(const char* data, size_t data_length, bool /*last*/, - Callback callback) override; - }; - -#ifdef CPPHTTPLIB_ZLIB_SUPPORT - class gzip_compressor final : public compressor { - public: - gzip_compressor(); - ~gzip_compressor() override; - - bool compress(const char* data, size_t data_length, bool last, - Callback callback) override; - - private: - bool is_valid_ = false; - z_stream strm_; - }; - - class gzip_decompressor final : public decompressor { - public: - gzip_decompressor(); - ~gzip_decompressor() override; - - bool is_valid() const override; - - bool decompress(const char* data, size_t data_length, Callback callback) override; - - private: - bool is_valid_ = false; - z_stream strm_; - }; -#endif - -#ifdef CPPHTTPLIB_BROTLI_SUPPORT - class brotli_compressor final : public compressor { - public: - brotli_compressor(); - ~brotli_compressor(); - - bool compress(const char* data, size_t data_length, bool last, - Callback callback) override; - - private: - BrotliEncoderState* state_ = nullptr; - }; - - class brotli_decompressor final : public decompressor { - public: - brotli_decompressor(); - ~brotli_decompressor(); - - bool is_valid() const override; - - bool decompress(const char* data, size_t data_length, Callback callback) override; - - private: - BrotliDecoderResult decoder_r; - BrotliDecoderState* decoder_s = nullptr; - }; -#endif - -#ifdef CPPHTTPLIB_ZSTD_SUPPORT - class zstd_compressor : public compressor { - public: - zstd_compressor(); - ~zstd_compressor(); - - bool compress(const char* data, size_t data_length, bool last, - Callback callback) override; - - private: - ZSTD_CCtx* ctx_ = nullptr; - }; - - class zstd_decompressor : public decompressor { - public: - zstd_decompressor(); - ~zstd_decompressor(); - - bool is_valid() const override; - - bool decompress(const char* data, size_t data_length, Callback callback) override; - - private: - ZSTD_DCtx* ctx_ = nullptr; - }; -#endif - - // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer` - // to store data. The call can set memory on stack for performance. - class stream_line_reader { - public: - stream_line_reader(Stream& strm, char* fixed_buffer, size_t fixed_buffer_size); - const char* ptr() const; - size_t size() const; - bool end_with_crlf() const; - bool getline(); - - private: - void append(char c); - - Stream& strm_; - char* fixed_buffer_; - const size_t fixed_buffer_size_; - size_t fixed_buffer_used_size_ = 0; - std::string growable_buffer_; - }; - - class mmap { - public: - mmap(const char* path); - ~mmap(); - - bool open(const char* path); - void close(); - - bool is_open() const; - size_t size() const; - const char* data() const; - - private: -#if defined(_WIN32) - HANDLE hFile_ = NULL; - HANDLE hMapping_ = NULL; -#else - int fd_ = -1; -#endif - size_t size_ = 0; - void* addr_ = nullptr; - bool is_open_empty_file = false; - }; - - // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5 - namespace fields { - - inline bool is_token_char(char c) { - return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' || - c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' || c == '.' || - c == '^' || c == '_' || c == '`' || c == '|' || c == '~'; - } - - inline bool is_token(const std::string& s) { - if (s.empty()) { - return false; - } - for (auto c : s) { - if (!is_token_char(c)) { - return false; - } - } - return true; - } - - inline bool is_field_name(const std::string& s) { return is_token(s); } - - inline bool is_vchar(char c) { return c >= 33 && c <= 126; } - - inline bool is_obs_text(char c) { return 128 <= static_cast(c); } - - inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); } - - inline bool is_field_content(const std::string& s) { - if (s.empty()) { - return true; - } - - if (s.size() == 1) { - return is_field_vchar(s[0]); - } else if (s.size() == 2) { - return is_field_vchar(s[0]) && is_field_vchar(s[1]); - } else { - size_t i = 0; - - if (!is_field_vchar(s[i])) { - return false; - } - i++; - - while (i < s.size() - 1) { - auto c = s[i++]; - if (c == ' ' || c == '\t' || is_field_vchar(c)) { - } else { - return false; - } - } - - return is_field_vchar(s[i]); - } - } - - inline bool is_field_value(const std::string& s) { return is_field_content(s); } - - } // namespace fields - - } // namespace detail - - // ---------------------------------------------------------------------------- - - /* - * Implementation that will be part of the .cc file if split into .h + .cc. - */ - - namespace detail { - - inline bool is_hex(char c, int& v) { - if (0x20 <= c && isdigit(c)) { - v = c - '0'; - return true; - } else if ('A' <= c && c <= 'F') { - v = c - 'A' + 10; - return true; - } else if ('a' <= c && c <= 'f') { - v = c - 'a' + 10; - return true; - } - return false; - } - - inline bool from_hex_to_i(const std::string& s, size_t i, size_t cnt, int& val) { - if (i >= s.size()) { - return false; - } - - val = 0; - for (; cnt; i++, cnt--) { - if (!s[i]) { - return false; - } - auto v = 0; - if (is_hex(s[i], v)) { - val = val * 16 + v; - } else { - return false; - } - } - return true; - } - - inline std::string from_i_to_hex(size_t n) { - static const auto charset = "0123456789abcdef"; - std::string ret; - do { - ret = charset[n & 15] + ret; - n >>= 4; - } while (n > 0); - return ret; - } - - inline size_t to_utf8(int code, char* buff) { - if (code < 0x0080) { - buff[0] = static_cast(code & 0x7F); - return 1; - } else if (code < 0x0800) { - buff[0] = static_cast(0xC0 | ((code >> 6) & 0x1F)); - buff[1] = static_cast(0x80 | (code & 0x3F)); - return 2; - } else if (code < 0xD800) { - buff[0] = static_cast(0xE0 | ((code >> 12) & 0xF)); - buff[1] = static_cast(0x80 | ((code >> 6) & 0x3F)); - buff[2] = static_cast(0x80 | (code & 0x3F)); - return 3; - } else if (code < 0xE000) { // D800 - DFFF is invalid... - return 0; - } else if (code < 0x10000) { - buff[0] = static_cast(0xE0 | ((code >> 12) & 0xF)); - buff[1] = static_cast(0x80 | ((code >> 6) & 0x3F)); - buff[2] = static_cast(0x80 | (code & 0x3F)); - return 3; - } else if (code < 0x110000) { - buff[0] = static_cast(0xF0 | ((code >> 18) & 0x7)); - buff[1] = static_cast(0x80 | ((code >> 12) & 0x3F)); - buff[2] = static_cast(0x80 | ((code >> 6) & 0x3F)); - buff[3] = static_cast(0x80 | (code & 0x3F)); - return 4; - } - - // NOTREACHED - return 0; - } - - // NOTE: This code came up with the following stackoverflow post: - // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c - inline std::string base64_encode(const std::string& in) { - static const auto lookup = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - std::string out; - out.reserve(in.size()); - - auto val = 0; - auto valb = -6; - - for (auto c : in) { - val = (val << 8) + static_cast(c); - valb += 8; - while (valb >= 0) { - out.push_back(lookup[(val >> valb) & 0x3F]); - valb -= 6; - } - } - - if (valb > -6) { - out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); - } - - while (out.size() % 4) { - out.push_back('='); - } - - return out; - } - - inline bool is_valid_path(const std::string& path) { - size_t level = 0; - size_t i = 0; - - // Skip slash - while (i < path.size() && path[i] == '/') { - i++; - } - - while (i < path.size()) { - // Read component - auto beg = i; - while (i < path.size() && path[i] != '/') { - if (path[i] == '\0') { - return false; - } else if (path[i] == '\\') { - return false; - } - i++; - } - - auto len = i - beg; - assert(len > 0); - - if (!path.compare(beg, len, ".")) { - ; - } else if (!path.compare(beg, len, "..")) { - if (level == 0) { - return false; - } - level--; - } else { - level++; - } - - // Skip slash - while (i < path.size() && path[i] == '/') { - i++; - } - } - - return true; - } - - inline FileStat::FileStat(const std::string& path) { -#if defined(_WIN32) - auto wpath = u8string_to_wstring(path.c_str()); - ret_ = _wstat(wpath.c_str(), &st_); -#else - ret_ = stat(path.c_str(), &st_); -#endif - } - inline bool FileStat::is_file() const { return ret_ >= 0 && S_ISREG(st_.st_mode); } - inline bool FileStat::is_dir() const { return ret_ >= 0 && S_ISDIR(st_.st_mode); } - - inline std::string encode_path(const std::string& s) { - std::string result; - result.reserve(s.size()); - - for (size_t i = 0; s[i]; i++) { - switch (s[i]) { - case ' ': - result += "%20"; - break; - case '+': - result += "%2B"; - break; - case '\r': - result += "%0D"; - break; - case '\n': - result += "%0A"; - break; - case '\'': - result += "%27"; - break; - case ',': - result += "%2C"; - break; - // case ':': result += "%3A"; break; // ok? probably... - case ';': - result += "%3B"; - break; - default: - auto c = static_cast(s[i]); - if (c >= 0x80) { - result += '%'; - char hex[4]; - auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c); - assert(len == 2); - result.append(hex, static_cast(len)); - } else { - result += s[i]; - } - break; - } - } - - return result; - } - - inline std::string file_extension(const std::string& path) { - std::smatch m; - thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$"); - if (std::regex_search(path, m, re)) { - return m[1].str(); - } - return std::string(); - } - - inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; } - - inline std::pair trim(const char* b, const char* e, size_t left, - size_t right) { - while (b + left < e && is_space_or_tab(b[left])) { - left++; - } - while (right > 0 && is_space_or_tab(b[right - 1])) { - right--; - } - return std::make_pair(left, right); - } - - inline std::string trim_copy(const std::string& s) { - auto r = trim(s.data(), s.data() + s.size(), 0, s.size()); - return s.substr(r.first, r.second - r.first); - } - - inline std::string trim_double_quotes_copy(const std::string& s) { - if (s.length() >= 2 && s.front() == '"' && s.back() == '"') { - return s.substr(1, s.size() - 2); - } - return s; - } - - inline void divide( - const char* data, std::size_t size, char d, - std::function fn) { - const auto it = std::find(data, data + size, d); - const auto found = static_cast(it != data + size); - const auto lhs_data = data; - const auto lhs_size = static_cast(it - data); - const auto rhs_data = it + found; - const auto rhs_size = size - lhs_size - found; - - fn(lhs_data, lhs_size, rhs_data, rhs_size); - } - - inline void divide( - const std::string& str, char d, - std::function fn) { - divide(str.data(), str.size(), d, std::move(fn)); - } - - inline void split(const char* b, const char* e, char d, - std::function fn) { - return split(b, e, d, (std::numeric_limits::max)(), std::move(fn)); - } - - inline void split(const char* b, const char* e, char d, size_t m, - std::function fn) { - size_t i = 0; - size_t beg = 0; - size_t count = 1; - - while (e ? (b + i < e) : (b[i] != '\0')) { - if (b[i] == d && count < m) { - auto r = trim(b, e, beg, i); - if (r.first < r.second) { - fn(&b[r.first], &b[r.second]); - } - beg = i + 1; - count++; - } - i++; - } - - if (i) { - auto r = trim(b, e, beg, i); - if (r.first < r.second) { - fn(&b[r.first], &b[r.second]); - } - } - } - - inline stream_line_reader::stream_line_reader(Stream& strm, char* fixed_buffer, - size_t fixed_buffer_size) - : strm_(strm), fixed_buffer_(fixed_buffer), fixed_buffer_size_(fixed_buffer_size) {} - - inline const char* stream_line_reader::ptr() const { - if (growable_buffer_.empty()) { - return fixed_buffer_; - } else { - return growable_buffer_.data(); - } - } - - inline size_t stream_line_reader::size() const { - if (growable_buffer_.empty()) { - return fixed_buffer_used_size_; - } else { - return growable_buffer_.size(); - } - } - - inline bool stream_line_reader::end_with_crlf() const { - auto end = ptr() + size(); - return size() >= 2 && end[-2] == '\r' && end[-1] == '\n'; - } - - inline bool stream_line_reader::getline() { - fixed_buffer_used_size_ = 0; - growable_buffer_.clear(); - -#ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR - char prev_byte = 0; -#endif - - for (size_t i = 0;; i++) { - if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) { - // Treat exceptionally long lines as an error to - // prevent infinite loops/memory exhaustion - return false; - } - char byte; - auto n = strm_.read(&byte, 1); - - if (n < 0) { - return false; - } else if (n == 0) { - if (i == 0) { - return false; - } else { - break; - } - } - - append(byte); - -#ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR - if (byte == '\n') { - break; - } -#else - if (prev_byte == '\r' && byte == '\n') { - break; - } - prev_byte = byte; -#endif - } - - return true; - } - - inline void stream_line_reader::append(char c) { - if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) { - fixed_buffer_[fixed_buffer_used_size_++] = c; - fixed_buffer_[fixed_buffer_used_size_] = '\0'; - } else { - if (growable_buffer_.empty()) { - assert(fixed_buffer_[fixed_buffer_used_size_] == '\0'); - growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_); - } - growable_buffer_ += c; - } - } - - inline mmap::mmap(const char* path) { open(path); } - - inline mmap::~mmap() { close(); } - - inline bool mmap::open(const char* path) { - close(); - -#if defined(_WIN32) - auto wpath = u8string_to_wstring(path); - if (wpath.empty()) { - return false; - } - - hFile_ = - ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, NULL); - - if (hFile_ == INVALID_HANDLE_VALUE) { - return false; - } - - LARGE_INTEGER size{}; - if (!::GetFileSizeEx(hFile_, &size)) { - return false; - } - // If the following line doesn't compile due to QuadPart, update Windows SDK. - // See: - // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721 - if (static_cast(size.QuadPart) > - (std::numeric_limits::max)()) { - // `size_t` might be 32-bits, on 32-bits Windows. - return false; - } - size_ = static_cast(size.QuadPart); - - hMapping_ = ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL); - - // Special treatment for an empty file... - if (hMapping_ == NULL && size_ == 0) { - close(); - is_open_empty_file = true; - return true; - } - - if (hMapping_ == NULL) { - close(); - return false; - } - - addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0); - - if (addr_ == nullptr) { - close(); - return false; - } -#else - fd_ = ::open(path, O_RDONLY); - if (fd_ == -1) { - return false; - } - - struct stat sb; - if (fstat(fd_, &sb) == -1) { - close(); - return false; - } - size_ = static_cast(sb.st_size); - - addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0); - - // Special treatment for an empty file... - if (addr_ == MAP_FAILED && size_ == 0) { - close(); - is_open_empty_file = true; - return false; - } -#endif - - return true; - } - - inline bool mmap::is_open() const { return is_open_empty_file ? true : addr_ != nullptr; } - - inline size_t mmap::size() const { return size_; } - - inline const char* mmap::data() const { - return is_open_empty_file ? "" : static_cast(addr_); - } - - inline void mmap::close() { -#if defined(_WIN32) - if (addr_) { - ::UnmapViewOfFile(addr_); - addr_ = nullptr; - } - - if (hMapping_) { - ::CloseHandle(hMapping_); - hMapping_ = NULL; - } - - if (hFile_ != INVALID_HANDLE_VALUE) { - ::CloseHandle(hFile_); - hFile_ = INVALID_HANDLE_VALUE; - } - - is_open_empty_file = false; -#else - if (addr_ != nullptr) { - munmap(addr_, size_); - addr_ = nullptr; - } - - if (fd_ != -1) { - ::close(fd_); - fd_ = -1; - } -#endif - size_ = 0; - } - inline int close_socket(socket_t sock) { -#ifdef _WIN32 - return closesocket(sock); -#else - return close(sock); -#endif - } - - template - inline ssize_t handle_EINTR(T fn) { - ssize_t res = 0; - while (true) { - res = fn(); - if (res < 0 && errno == EINTR) { - std::this_thread::sleep_for(std::chrono::microseconds{1}); - continue; - } - break; - } - return res; - } - - inline ssize_t read_socket(socket_t sock, void* ptr, size_t size, int flags) { - return handle_EINTR([&]() { - return recv(sock, -#ifdef _WIN32 - static_cast(ptr), static_cast(size), -#else - ptr, size, -#endif - flags); - }); - } - - inline ssize_t send_socket(socket_t sock, const void* ptr, size_t size, int flags) { - return handle_EINTR([&]() { - return send(sock, -#ifdef _WIN32 - static_cast(ptr), static_cast(size), -#else - ptr, size, -#endif - flags); - }); - } - - inline int poll_wrapper(struct pollfd* fds, nfds_t nfds, int timeout) { -#ifdef _WIN32 - return ::WSAPoll(fds, nfds, timeout); -#else - return ::poll(fds, nfds, timeout); -#endif - } - - template - inline ssize_t select_impl(socket_t sock, time_t sec, time_t usec) { -#ifdef __APPLE__ - if (sock >= FD_SETSIZE) { - return -1; - } - - fd_set fds, *rfds, *wfds; - FD_ZERO(&fds); - FD_SET(sock, &fds); - rfds = (Read ? &fds : nullptr); - wfds = (Read ? nullptr : &fds); - - timeval tv; - tv.tv_sec = static_cast(sec); - tv.tv_usec = static_cast(usec); - - return handle_EINTR( - [&]() { return select(static_cast(sock + 1), rfds, wfds, nullptr, &tv); }); -#else - struct pollfd pfd; - pfd.fd = sock; - pfd.events = (Read ? POLLIN : POLLOUT); - - auto timeout = static_cast(sec * 1000 + usec / 1000); - - return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); }); -#endif - } - - inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) { - return select_impl(sock, sec, usec); - } - - inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) { - return select_impl(sock, sec, usec); - } - - inline Error wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec) { -#ifdef __APPLE__ - if (sock >= FD_SETSIZE) { - return Error::Connection; - } - - fd_set fdsr, fdsw; - FD_ZERO(&fdsr); - FD_ZERO(&fdsw); - FD_SET(sock, &fdsr); - FD_SET(sock, &fdsw); - - timeval tv; - tv.tv_sec = static_cast(sec); - tv.tv_usec = static_cast(usec); - - auto ret = handle_EINTR( - [&]() { return select(static_cast(sock + 1), &fdsr, &fdsw, nullptr, &tv); }); - - if (ret == 0) { - return Error::ConnectionTimeout; - } - - if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) { - auto error = 0; - socklen_t len = sizeof(error); - auto res = - getsockopt(sock, SOL_SOCKET, SO_ERROR, reinterpret_cast(&error), &len); - auto successful = res >= 0 && !error; - return successful ? Error::Success : Error::Connection; - } - - return Error::Connection; -#else - struct pollfd pfd_read; - pfd_read.fd = sock; - pfd_read.events = POLLIN | POLLOUT; - - auto timeout = static_cast(sec * 1000 + usec / 1000); - - auto poll_res = handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); }); - - if (poll_res == 0) { - return Error::ConnectionTimeout; - } - - if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) { - auto error = 0; - socklen_t len = sizeof(error); - auto res = - getsockopt(sock, SOL_SOCKET, SO_ERROR, reinterpret_cast(&error), &len); - auto successful = res >= 0 && !error; - return successful ? Error::Success : Error::Connection; - } - - return Error::Connection; -#endif - } - - inline bool is_socket_alive(socket_t sock) { - const auto val = detail::select_read(sock, 0, 0); - if (val == 0) { - return true; - } else if (val < 0 && errno == EBADF) { - return false; - } - char buf[1]; - return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0; - } - - class SocketStream final : public Stream { - public: - SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec, - time_t write_timeout_sec, time_t write_timeout_usec, - time_t max_timeout_msec = 0, - std::chrono::time_point start_time = - (std::chrono::steady_clock::time_point::min)()); - ~SocketStream() override; - - bool is_readable() const override; - bool wait_readable() const override; - bool wait_writable() const override; - ssize_t read(char* ptr, size_t size) override; - ssize_t write(const char* ptr, size_t size) override; - void get_remote_ip_and_port(std::string& ip, int& port) const override; - void get_local_ip_and_port(std::string& ip, int& port) const override; - socket_t socket() const override; - time_t duration() const override; - - private: - socket_t sock_; - time_t read_timeout_sec_; - time_t read_timeout_usec_; - time_t write_timeout_sec_; - time_t write_timeout_usec_; - time_t max_timeout_msec_; - const std::chrono::time_point start_time_; - - std::vector read_buff_; - size_t read_buff_off_ = 0; - size_t read_buff_content_size_ = 0; - - static const size_t read_buff_size_ = 1024l * 4; - }; - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - class SSLSocketStream final : public Stream { - public: - SSLSocketStream(socket_t sock, SSL* ssl, time_t read_timeout_sec, - time_t read_timeout_usec, time_t write_timeout_sec, - time_t write_timeout_usec, time_t max_timeout_msec = 0, - std::chrono::time_point start_time = - (std::chrono::steady_clock::time_point::min)()); - ~SSLSocketStream() override; - - bool is_readable() const override; - bool wait_readable() const override; - bool wait_writable() const override; - ssize_t read(char* ptr, size_t size) override; - ssize_t write(const char* ptr, size_t size) override; - void get_remote_ip_and_port(std::string& ip, int& port) const override; - void get_local_ip_and_port(std::string& ip, int& port) const override; - socket_t socket() const override; - time_t duration() const override; - - private: - socket_t sock_; - SSL* ssl_; - time_t read_timeout_sec_; - time_t read_timeout_usec_; - time_t write_timeout_sec_; - time_t write_timeout_usec_; - time_t max_timeout_msec_; - const std::chrono::time_point start_time_; - }; -#endif - - inline bool keep_alive(const std::atomic& svr_sock, socket_t sock, - time_t keep_alive_timeout_sec) { - using namespace std::chrono; - - const auto interval_usec = CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND; - - // Avoid expensive `steady_clock::now()` call for the first time - if (select_read(sock, 0, interval_usec) > 0) { - return true; - } - - const auto start = steady_clock::now() - microseconds{interval_usec}; - const auto timeout = seconds{keep_alive_timeout_sec}; - - while (true) { - if (svr_sock == INVALID_SOCKET) { - break; // Server socket is closed - } - - auto val = select_read(sock, 0, interval_usec); - if (val < 0) { - break; // Ssocket error - } else if (val == 0) { - if (steady_clock::now() - start > timeout) { - break; // Timeout - } - } else { - return true; // Ready for read - } - } - - return false; - } - - template - inline bool process_server_socket_core(const std::atomic& svr_sock, socket_t sock, - size_t keep_alive_max_count, - time_t keep_alive_timeout_sec, T callback) { - assert(keep_alive_max_count > 0); - auto ret = false; - auto count = keep_alive_max_count; - while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) { - auto close_connection = count == 1; - auto connection_closed = false; - ret = callback(close_connection, connection_closed); - if (!ret || connection_closed) { - break; - } - count--; - } - return ret; - } - - template - inline bool process_server_socket(const std::atomic& svr_sock, socket_t sock, - size_t keep_alive_max_count, - time_t keep_alive_timeout_sec, time_t read_timeout_sec, - time_t read_timeout_usec, time_t write_timeout_sec, - time_t write_timeout_usec, T callback) { - return process_server_socket_core( - svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec, - [&](bool close_connection, bool& connection_closed) { - SocketStream strm(sock, read_timeout_sec, read_timeout_usec, write_timeout_sec, - write_timeout_usec); - return callback(strm, close_connection, connection_closed); - }); - } - - inline bool process_client_socket( - socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec, - time_t write_timeout_sec, time_t write_timeout_usec, time_t max_timeout_msec, - std::chrono::time_point start_time, - std::function callback) { - SocketStream strm(sock, read_timeout_sec, read_timeout_usec, write_timeout_sec, - write_timeout_usec, max_timeout_msec, start_time); - return callback(strm); - } - - inline int shutdown_socket(socket_t sock) { -#ifdef _WIN32 - return shutdown(sock, SD_BOTH); -#else - return shutdown(sock, SHUT_RDWR); -#endif - } - - inline std::string escape_abstract_namespace_unix_domain(const std::string& s) { - if (s.size() > 1 && s[0] == '\0') { - auto ret = s; - ret[0] = '@'; - return ret; - } - return s; - } - - inline std::string unescape_abstract_namespace_unix_domain(const std::string& s) { - if (s.size() > 1 && s[0] == '@') { - auto ret = s; - ret[0] = '\0'; - return ret; - } - return s; - } - - inline int getaddrinfo_with_timeout(const char* node, const char* service, - const struct addrinfo* hints, struct addrinfo** res, - time_t timeout_sec) { -#ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO - if (timeout_sec <= 0) { - // No timeout specified, use standard getaddrinfo - return getaddrinfo(node, service, hints, res); - } - -#ifdef _WIN32 - // Windows-specific implementation using GetAddrInfoEx with overlapped I/O - OVERLAPPED overlapped = {0}; - HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr); - if (!event) { - return EAI_FAIL; - } - - overlapped.hEvent = event; - - PADDRINFOEXW result_addrinfo = nullptr; - HANDLE cancel_handle = nullptr; - - ADDRINFOEXW hints_ex = {0}; - if (hints) { - hints_ex.ai_flags = hints->ai_flags; - hints_ex.ai_family = hints->ai_family; - hints_ex.ai_socktype = hints->ai_socktype; - hints_ex.ai_protocol = hints->ai_protocol; - } - - auto wnode = u8string_to_wstring(node); - auto wservice = u8string_to_wstring(service); - - auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr, - hints ? &hints_ex : nullptr, &result_addrinfo, nullptr, - &overlapped, nullptr, &cancel_handle); - - if (ret == WSA_IO_PENDING) { - auto wait_result = - ::WaitForSingleObject(event, static_cast(timeout_sec * 1000)); - if (wait_result == WAIT_TIMEOUT) { - if (cancel_handle) { - ::GetAddrInfoExCancel(&cancel_handle); - } - ::CloseHandle(event); - return EAI_AGAIN; - } - - DWORD bytes_returned; - if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped, &bytes_returned, - FALSE)) { - ::CloseHandle(event); - return ::WSAGetLastError(); - } - } - - ::CloseHandle(event); - - if (ret == NO_ERROR || ret == WSA_IO_PENDING) { - *res = reinterpret_cast(result_addrinfo); - return 0; - } - - return ret; -#elif TARGET_OS_MAC - // macOS implementation using CFHost API for asynchronous DNS resolution - CFStringRef hostname_ref = - CFStringCreateWithCString(kCFAllocatorDefault, node, kCFStringEncodingUTF8); - if (!hostname_ref) { - return EAI_MEMORY; - } - - CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref); - CFRelease(hostname_ref); - if (!host_ref) { - return EAI_MEMORY; - } - - // Set up context for callback - struct CFHostContext { - bool completed = false; - bool success = false; - CFArrayRef addresses = nullptr; - std::mutex mutex; - std::condition_variable cv; - } context; - - CFHostClientContext client_context; - memset(&client_context, 0, sizeof(client_context)); - client_context.info = &context; - - // Set callback - auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/, - const CFStreamError* error, void* info) { - auto ctx = static_cast(info); - std::lock_guard lock(ctx->mutex); - - if (error && error->error != 0) { - ctx->success = false; - } else { - Boolean hasBeenResolved; - ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved); - if (ctx->addresses && hasBeenResolved) { - CFRetain(ctx->addresses); - ctx->success = true; - } else { - ctx->success = false; - } - } - ctx->completed = true; - ctx->cv.notify_one(); - }; - - if (!CFHostSetClient(host_ref, callback, &client_context)) { - CFRelease(host_ref); - return EAI_SYSTEM; - } - - // Schedule on run loop - CFRunLoopRef run_loop = CFRunLoopGetCurrent(); - CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode); - - // Start resolution - CFStreamError stream_error; - if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) { - CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode); - CFRelease(host_ref); - return EAI_FAIL; - } - - // Wait for completion with timeout - auto timeout_time = - std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec); - bool timed_out = false; - - { - std::unique_lock lock(context.mutex); - - while (!context.completed) { - auto now = std::chrono::steady_clock::now(); - if (now >= timeout_time) { - timed_out = true; - break; - } - - // Run the runloop for a short time - lock.unlock(); - CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true); - lock.lock(); - } - } - - // Clean up - CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode); - CFHostSetClient(host_ref, nullptr, nullptr); - - if (timed_out || !context.completed) { - CFHostCancelInfoResolution(host_ref, kCFHostAddresses); - CFRelease(host_ref); - return EAI_AGAIN; - } - - if (!context.success || !context.addresses) { - CFRelease(host_ref); - return EAI_NODATA; - } - - // Convert CFArray to addrinfo - CFIndex count = CFArrayGetCount(context.addresses); - if (count == 0) { - CFRelease(context.addresses); - CFRelease(host_ref); - return EAI_NODATA; - } - - struct addrinfo* result_addrinfo = nullptr; - struct addrinfo** current = &result_addrinfo; - - for (CFIndex i = 0; i < count; i++) { - CFDataRef addr_data = - static_cast(CFArrayGetValueAtIndex(context.addresses, i)); - if (!addr_data) - continue; - - const struct sockaddr* sockaddr_ptr = - reinterpret_cast(CFDataGetBytePtr(addr_data)); - socklen_t sockaddr_len = static_cast(CFDataGetLength(addr_data)); - - // Allocate addrinfo structure - *current = static_cast(malloc(sizeof(struct addrinfo))); - if (!*current) { - freeaddrinfo(result_addrinfo); - CFRelease(context.addresses); - CFRelease(host_ref); - return EAI_MEMORY; - } - - memset(*current, 0, sizeof(struct addrinfo)); - - // Set up addrinfo fields - (*current)->ai_family = sockaddr_ptr->sa_family; - (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM; - (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP; - (*current)->ai_addrlen = sockaddr_len; - - // Copy sockaddr - (*current)->ai_addr = static_cast(malloc(sockaddr_len)); - if (!(*current)->ai_addr) { - freeaddrinfo(result_addrinfo); - CFRelease(context.addresses); - CFRelease(host_ref); - return EAI_MEMORY; - } - memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len); - - // Set port if service is specified - if (service && strlen(service) > 0) { - int port = atoi(service); - if (port > 0) { - if (sockaddr_ptr->sa_family == AF_INET) { - reinterpret_cast((*current)->ai_addr)->sin_port = - htons(static_cast(port)); - } else if (sockaddr_ptr->sa_family == AF_INET6) { - reinterpret_cast((*current)->ai_addr)->sin6_port = - htons(static_cast(port)); - } - } - } - - current = &((*current)->ai_next); - } - - CFRelease(context.addresses); - CFRelease(host_ref); - - *res = result_addrinfo; - return 0; -#elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \ - (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2)) - // Linux implementation using getaddrinfo_a for asynchronous DNS resolution - struct gaicb request; - struct gaicb* requests[1] = {&request}; - struct sigevent sevp; - struct timespec timeout; - - // Initialize the request structure - memset(&request, 0, sizeof(request)); - request.ar_name = node; - request.ar_service = service; - request.ar_request = hints; - - // Set up timeout - timeout.tv_sec = timeout_sec; - timeout.tv_nsec = 0; - - // Initialize sigevent structure (not used, but required) - memset(&sevp, 0, sizeof(sevp)); - sevp.sigev_notify = SIGEV_NONE; - - // Start asynchronous resolution - int start_result = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp); - if (start_result != 0) { - return start_result; - } - - // Wait for completion with timeout - int wait_result = gai_suspend((const struct gaicb* const*)requests, 1, &timeout); - - if (wait_result == 0 || wait_result == EAI_ALLDONE) { - // Completed successfully, get the result - int gai_result = gai_error(&request); - if (gai_result == 0) { - *res = request.ar_result; - return 0; - } else { - // Clean up on error - if (request.ar_result) { - freeaddrinfo(request.ar_result); - } - return gai_result; - } - } else if (wait_result == EAI_AGAIN) { - // Timeout occurred, cancel the request - gai_cancel(&request); - return EAI_AGAIN; - } else { - // Other error occurred - gai_cancel(&request); - return wait_result; - } -#else - // Fallback implementation using thread-based timeout for other Unix systems - - struct GetAddrInfoState { - ~GetAddrInfoState() { - if (info) { - freeaddrinfo(info); - } - } - - std::mutex mutex; - std::condition_variable result_cv; - bool completed = false; - int result = EAI_SYSTEM; - std::string node; - std::string service; - struct addrinfo hints; - struct addrinfo* info = nullptr; - }; - - // Allocate on the heap, so the resolver thread can keep using the data. - auto state = std::make_shared(); - state->node = node; - state->service = service; - state->hints = *hints; - - std::thread resolve_thread([state]() { - auto thread_result = getaddrinfo(state->node.c_str(), state->service.c_str(), - &state->hints, &state->info); - - std::lock_guard lock(state->mutex); - state->result = thread_result; - state->completed = true; - state->result_cv.notify_one(); - }); - - // Wait for completion or timeout - std::unique_lock lock(state->mutex); - auto finished = state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec), - [&] { return state->completed; }); - - if (finished) { - // Operation completed within timeout - resolve_thread.join(); - *res = state->info; - state->info = nullptr; // Pass ownership to caller - return state->result; - } else { - // Timeout occurred - resolve_thread.detach(); // Let the thread finish in background - return EAI_AGAIN; // Return timeout error - } -#endif -#else - (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo - return getaddrinfo(node, service, hints, res); -#endif - } - - template - socket_t create_socket(const std::string& host, const std::string& ip, int port, - int address_family, int socket_flags, bool tcp_nodelay, - bool ipv6_v6only, SocketOptions socket_options, - BindOrConnect bind_or_connect, time_t timeout_sec = 0) { - // Get address info - const char* node = nullptr; - struct addrinfo hints; - struct addrinfo* result; - - memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = IPPROTO_IP; - - if (!ip.empty()) { - node = ip.c_str(); - // Ask getaddrinfo to convert IP in c-string to address - hints.ai_family = AF_UNSPEC; - hints.ai_flags = AI_NUMERICHOST; - } else { - if (!host.empty()) { - node = host.c_str(); - } - hints.ai_family = address_family; - hints.ai_flags = socket_flags; - } - -#if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H) - if (hints.ai_family == AF_UNIX) { - const auto addrlen = host.length(); - if (addrlen > sizeof(sockaddr_un::sun_path)) { - return INVALID_SOCKET; - } - -#ifdef SOCK_CLOEXEC - auto sock = - socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC, hints.ai_protocol); -#else - auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol); -#endif - - if (sock != INVALID_SOCKET) { - sockaddr_un addr{}; - addr.sun_family = AF_UNIX; - - auto unescaped_host = unescape_abstract_namespace_unix_domain(host); - std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path); - - hints.ai_addr = reinterpret_cast(&addr); - hints.ai_addrlen = - static_cast(sizeof(addr) - sizeof(addr.sun_path) + addrlen); - -#ifndef SOCK_CLOEXEC -#ifndef _WIN32 - fcntl(sock, F_SETFD, FD_CLOEXEC); -#endif -#endif - - if (socket_options) { - socket_options(sock); - } - -#ifdef _WIN32 - // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so - // remove the option. - detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0); -#endif - - bool dummy; - if (!bind_or_connect(sock, hints, dummy)) { - close_socket(sock); - sock = INVALID_SOCKET; - } - } - return sock; - } -#endif - - auto service = std::to_string(port); - - if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result, timeout_sec)) { -#if defined __linux__ && !defined __ANDROID__ - res_init(); -#endif - return INVALID_SOCKET; - } - auto se = detail::scope_exit([&] { freeaddrinfo(result); }); - - for (auto rp = result; rp; rp = rp->ai_next) { - // Create a socket -#ifdef _WIN32 - auto sock = WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0, - WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED); - /** - * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1 - * and above the socket creation fails on older Windows Systems. - * - * Let's try to create a socket the old way in this case. - * - * Reference: - * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa - * - * WSA_FLAG_NO_HANDLE_INHERIT: - * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with - * SP1, and later - * - */ - if (sock == INVALID_SOCKET) { - sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); - } -#else - -#ifdef SOCK_CLOEXEC - auto sock = socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol); -#else - auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); -#endif - -#endif - if (sock == INVALID_SOCKET) { - continue; - } - -#if !defined _WIN32 && !defined SOCK_CLOEXEC - if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) { - close_socket(sock); - continue; - } -#endif - - if (tcp_nodelay) { - set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); - } - - if (rp->ai_family == AF_INET6) { - set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0); - } - - if (socket_options) { - socket_options(sock); - } - - // bind or connect - auto quit = false; - if (bind_or_connect(sock, *rp, quit)) { - return sock; - } - - close_socket(sock); - - if (quit) { - break; - } - } - - return INVALID_SOCKET; - } - - inline void set_nonblocking(socket_t sock, bool nonblocking) { -#ifdef _WIN32 - auto flags = nonblocking ? 1UL : 0UL; - ioctlsocket(sock, FIONBIO, &flags); -#else - auto flags = fcntl(sock, F_GETFL, 0); - fcntl(sock, F_SETFL, nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK))); -#endif - } - - inline bool is_connection_error() { -#ifdef _WIN32 - return WSAGetLastError() != WSAEWOULDBLOCK; -#else - return errno != EINPROGRESS; -#endif - } - - inline bool bind_ip_address(socket_t sock, const std::string& host) { - struct addrinfo hints; - struct addrinfo* result; - - memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = 0; - - if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) { - return false; - } - - auto se = detail::scope_exit([&] { freeaddrinfo(result); }); - - auto ret = false; - for (auto rp = result; rp; rp = rp->ai_next) { - const auto& ai = *rp; - if (!::bind(sock, ai.ai_addr, static_cast(ai.ai_addrlen))) { - ret = true; - break; - } - } - - return ret; - } - -#if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__ -#define USE_IF2IP -#endif - -#ifdef USE_IF2IP - inline std::string if2ip(int address_family, const std::string& ifn) { - struct ifaddrs* ifap; - getifaddrs(&ifap); - auto se = detail::scope_exit([&] { freeifaddrs(ifap); }); - - std::string addr_candidate; - for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) { - if (ifa->ifa_addr && ifn == ifa->ifa_name && - (AF_UNSPEC == address_family || ifa->ifa_addr->sa_family == address_family)) { - if (ifa->ifa_addr->sa_family == AF_INET) { - auto sa = reinterpret_cast(ifa->ifa_addr); - char buf[INET_ADDRSTRLEN]; - if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) { - return std::string(buf, INET_ADDRSTRLEN); - } - } else if (ifa->ifa_addr->sa_family == AF_INET6) { - auto sa = reinterpret_cast(ifa->ifa_addr); - if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) { - char buf[INET6_ADDRSTRLEN] = {}; - if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) { - // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL - auto s6_addr_head = sa->sin6_addr.s6_addr[0]; - if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) { - addr_candidate = std::string(buf, INET6_ADDRSTRLEN); - } else { - return std::string(buf, INET6_ADDRSTRLEN); - } - } - } - } - } - } - return addr_candidate; - } -#endif - - inline socket_t create_client_socket(const std::string& host, const std::string& ip, - int port, int address_family, bool tcp_nodelay, - bool ipv6_v6only, SocketOptions socket_options, - time_t connection_timeout_sec, - time_t connection_timeout_usec, - time_t read_timeout_sec, time_t read_timeout_usec, - time_t write_timeout_sec, time_t write_timeout_usec, - const std::string& intf, Error& error) { - auto sock = create_socket( - host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only, - std::move(socket_options), - [&](socket_t sock2, struct addrinfo& ai, bool& quit) -> bool { - if (!intf.empty()) { -#ifdef USE_IF2IP - auto ip_from_if = if2ip(address_family, intf); - if (ip_from_if.empty()) { - ip_from_if = intf; - } - if (!bind_ip_address(sock2, ip_from_if)) { - error = Error::BindIPAddress; - return false; - } -#endif - } - - set_nonblocking(sock2, true); - - auto ret = ::connect(sock2, ai.ai_addr, static_cast(ai.ai_addrlen)); - - if (ret < 0) { - if (is_connection_error()) { - error = Error::Connection; - return false; - } - error = wait_until_socket_is_ready(sock2, connection_timeout_sec, - connection_timeout_usec); - if (error != Error::Success) { - if (error == Error::ConnectionTimeout) { - quit = true; - } - return false; - } - } - - set_nonblocking(sock2, false); - set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec, - read_timeout_usec); - set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec, - write_timeout_usec); - - error = Error::Success; - return true; - }, - connection_timeout_sec); // Pass DNS timeout - - if (sock != INVALID_SOCKET) { - error = Error::Success; - } else { - if (error == Error::Success) { - error = Error::Connection; - } - } - - return sock; - } - - inline bool get_ip_and_port(const struct sockaddr_storage& addr, socklen_t addr_len, - std::string& ip, int& port) { - if (addr.ss_family == AF_INET) { - port = ntohs(reinterpret_cast(&addr)->sin_port); - } else if (addr.ss_family == AF_INET6) { - port = ntohs(reinterpret_cast(&addr)->sin6_port); - } else { - return false; - } - - std::array ipstr{}; - if (getnameinfo(reinterpret_cast(&addr), addr_len, ipstr.data(), - static_cast(ipstr.size()), nullptr, 0, NI_NUMERICHOST)) { - return false; - } - - ip = ipstr.data(); - return true; - } - - inline void get_local_ip_and_port(socket_t sock, std::string& ip, int& port) { - struct sockaddr_storage addr; - socklen_t addr_len = sizeof(addr); - if (!getsockname(sock, reinterpret_cast(&addr), &addr_len)) { - get_ip_and_port(addr, addr_len, ip, port); - } - } - - inline void get_remote_ip_and_port(socket_t sock, std::string& ip, int& port) { - struct sockaddr_storage addr; - socklen_t addr_len = sizeof(addr); - - if (!getpeername(sock, reinterpret_cast(&addr), &addr_len)) { -#ifndef _WIN32 - if (addr.ss_family == AF_UNIX) { -#if defined(__linux__) - struct ucred ucred; - socklen_t len = sizeof(ucred); - if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) { - port = ucred.pid; - } -#elif defined(SOL_LOCAL) && defined(SO_PEERPID) - pid_t pid; - socklen_t len = sizeof(pid); - if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) { - port = pid; - } -#endif - return; - } -#endif - get_ip_and_port(addr, addr_len, ip, port); - } - } - - inline constexpr unsigned int str2tag_core(const char* s, size_t l, unsigned int h) { - return (l == 0) - ? h - : str2tag_core(s + 1, l - 1, - // Unsets the 6 high bits of h, therefore no overflow happens - (((std::numeric_limits::max)() >> 6) & h * 33) ^ - static_cast(*s)); - } - - inline unsigned int str2tag(const std::string& s) { - return str2tag_core(s.data(), s.size(), 0); - } - - namespace udl { - - inline constexpr unsigned int operator""_t(const char* s, size_t l) { - return str2tag_core(s, l, 0); - } - - } // namespace udl - - inline std::string find_content_type(const std::string& path, - const std::map& user_data, - const std::string& default_content_type) { - auto ext = file_extension(path); - - auto it = user_data.find(ext); - if (it != user_data.end()) { - return it->second; - } - - using udl::operator""_t; - - switch (str2tag(ext)) { - default: - return default_content_type; - - case "css"_t: - return "text/css"; - case "csv"_t: - return "text/csv"; - case "htm"_t: - case "html"_t: - return "text/html"; - case "js"_t: - case "mjs"_t: - return "text/javascript"; - case "txt"_t: - return "text/plain"; - case "vtt"_t: - return "text/vtt"; - - case "apng"_t: - return "image/apng"; - case "avif"_t: - return "image/avif"; - case "bmp"_t: - return "image/bmp"; - case "gif"_t: - return "image/gif"; - case "png"_t: - return "image/png"; - case "svg"_t: - return "image/svg+xml"; - case "webp"_t: - return "image/webp"; - case "ico"_t: - return "image/x-icon"; - case "tif"_t: - return "image/tiff"; - case "tiff"_t: - return "image/tiff"; - case "jpg"_t: - case "jpeg"_t: - return "image/jpeg"; - - case "mp4"_t: - return "video/mp4"; - case "mpeg"_t: - return "video/mpeg"; - case "webm"_t: - return "video/webm"; - - case "mp3"_t: - return "audio/mp3"; - case "mpga"_t: - return "audio/mpeg"; - case "weba"_t: - return "audio/webm"; - case "wav"_t: - return "audio/wave"; - - case "otf"_t: - return "font/otf"; - case "ttf"_t: - return "font/ttf"; - case "woff"_t: - return "font/woff"; - case "woff2"_t: - return "font/woff2"; - - case "7z"_t: - return "application/x-7z-compressed"; - case "atom"_t: - return "application/atom+xml"; - case "pdf"_t: - return "application/pdf"; - case "json"_t: - return "application/json"; - case "rss"_t: - return "application/rss+xml"; - case "tar"_t: - return "application/x-tar"; - case "xht"_t: - case "xhtml"_t: - return "application/xhtml+xml"; - case "xslt"_t: - return "application/xslt+xml"; - case "xml"_t: - return "application/xml"; - case "gz"_t: - return "application/gzip"; - case "zip"_t: - return "application/zip"; - case "wasm"_t: - return "application/wasm"; - } - } - - inline bool can_compress_content_type(const std::string& content_type) { - using udl::operator""_t; - - auto tag = str2tag(content_type); - - switch (tag) { - case "image/svg+xml"_t: - case "application/javascript"_t: - case "application/json"_t: - case "application/xml"_t: - case "application/protobuf"_t: - case "application/xhtml+xml"_t: - return true; - - case "text/event-stream"_t: - return false; - - default: - return !content_type.rfind("text/", 0); - } - } - - inline EncodingType encoding_type(const Request& req, const Response& res) { - auto ret = detail::can_compress_content_type(res.get_header_value("Content-Type")); - if (!ret) { - return EncodingType::None; - } - - const auto& s = req.get_header_value("Accept-Encoding"); - (void)(s); - -#ifdef CPPHTTPLIB_BROTLI_SUPPORT - // TODO: 'Accept-Encoding' has br, not br;q=0 - ret = s.find("br") != std::string::npos; - if (ret) { - return EncodingType::Brotli; - } -#endif - -#ifdef CPPHTTPLIB_ZLIB_SUPPORT - // TODO: 'Accept-Encoding' has gzip, not gzip;q=0 - ret = s.find("gzip") != std::string::npos; - if (ret) { - return EncodingType::Gzip; - } -#endif - -#ifdef CPPHTTPLIB_ZSTD_SUPPORT - // TODO: 'Accept-Encoding' has zstd, not zstd;q=0 - ret = s.find("zstd") != std::string::npos; - if (ret) { - return EncodingType::Zstd; - } -#endif - - return EncodingType::None; - } - - inline bool nocompressor::compress(const char* data, size_t data_length, bool /*last*/, - Callback callback) { - if (!data_length) { - return true; - } - return callback(data, data_length); - } - -#ifdef CPPHTTPLIB_ZLIB_SUPPORT - inline gzip_compressor::gzip_compressor() { - std::memset(&strm_, 0, sizeof(strm_)); - strm_.zalloc = Z_NULL; - strm_.zfree = Z_NULL; - strm_.opaque = Z_NULL; - - is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, - Z_DEFAULT_STRATEGY) == Z_OK; - } - - inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); } - - inline bool gzip_compressor::compress(const char* data, size_t data_length, bool last, - Callback callback) { - assert(is_valid_); - - do { - constexpr size_t max_avail_in = - (std::numeric_limits::max)(); - - strm_.avail_in = - static_cast((std::min)(data_length, max_avail_in)); - strm_.next_in = const_cast(reinterpret_cast(data)); - - data_length -= strm_.avail_in; - data += strm_.avail_in; - - auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH; - auto ret = Z_OK; - - std::array buff{}; - do { - strm_.avail_out = static_cast(buff.size()); - strm_.next_out = reinterpret_cast(buff.data()); - - ret = deflate(&strm_, flush); - if (ret == Z_STREAM_ERROR) { - return false; - } - - if (!callback(buff.data(), buff.size() - strm_.avail_out)) { - return false; - } - } while (strm_.avail_out == 0); - - assert((flush == Z_FINISH && ret == Z_STREAM_END) || - (flush == Z_NO_FLUSH && ret == Z_OK)); - assert(strm_.avail_in == 0); - } while (data_length > 0); - - return true; - } - - inline gzip_decompressor::gzip_decompressor() { - std::memset(&strm_, 0, sizeof(strm_)); - strm_.zalloc = Z_NULL; - strm_.zfree = Z_NULL; - strm_.opaque = Z_NULL; - - // 15 is the value of wbits, which should be at the maximum possible value - // to ensure that any gzip stream can be decoded. The offset of 32 specifies - // that the stream type should be automatically detected either gzip or - // deflate. - is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK; - } - - inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); } - - inline bool gzip_decompressor::is_valid() const { return is_valid_; } - - inline bool gzip_decompressor::decompress(const char* data, size_t data_length, - Callback callback) { - assert(is_valid_); - - auto ret = Z_OK; - - do { - constexpr size_t max_avail_in = - (std::numeric_limits::max)(); - - strm_.avail_in = - static_cast((std::min)(data_length, max_avail_in)); - strm_.next_in = const_cast(reinterpret_cast(data)); - - data_length -= strm_.avail_in; - data += strm_.avail_in; - - std::array buff{}; - while (strm_.avail_in > 0 && ret == Z_OK) { - strm_.avail_out = static_cast(buff.size()); - strm_.next_out = reinterpret_cast(buff.data()); - - ret = inflate(&strm_, Z_NO_FLUSH); - - assert(ret != Z_STREAM_ERROR); - switch (ret) { - case Z_NEED_DICT: - case Z_DATA_ERROR: - case Z_MEM_ERROR: - inflateEnd(&strm_); - return false; - } - - if (!callback(buff.data(), buff.size() - strm_.avail_out)) { - return false; - } - } - - if (ret != Z_OK && ret != Z_STREAM_END) { - return false; - } - - } while (data_length > 0); - - return true; - } -#endif - -#ifdef CPPHTTPLIB_BROTLI_SUPPORT - inline brotli_compressor::brotli_compressor() { - state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr); - } - - inline brotli_compressor::~brotli_compressor() { BrotliEncoderDestroyInstance(state_); } - - inline bool brotli_compressor::compress(const char* data, size_t data_length, bool last, - Callback callback) { - std::array buff{}; - - auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS; - auto available_in = data_length; - auto next_in = reinterpret_cast(data); - - for (;;) { - if (last) { - if (BrotliEncoderIsFinished(state_)) { - break; - } - } else { - if (!available_in) { - break; - } - } - - auto available_out = buff.size(); - auto next_out = buff.data(); - - if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in, - &available_out, &next_out, nullptr)) { - return false; - } - - auto output_bytes = buff.size() - available_out; - if (output_bytes) { - callback(reinterpret_cast(buff.data()), output_bytes); - } - } - - return true; - } - - inline brotli_decompressor::brotli_decompressor() { - decoder_s = BrotliDecoderCreateInstance(0, 0, 0); - decoder_r = - decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT : BROTLI_DECODER_RESULT_ERROR; - } - - inline brotli_decompressor::~brotli_decompressor() { - if (decoder_s) { - BrotliDecoderDestroyInstance(decoder_s); - } - } - - inline bool brotli_decompressor::is_valid() const { return decoder_s; } - - inline bool brotli_decompressor::decompress(const char* data, size_t data_length, - Callback callback) { - if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS || - decoder_r == BROTLI_DECODER_RESULT_ERROR) { - return 0; - } - - auto next_in = reinterpret_cast(data); - size_t avail_in = data_length; - size_t total_out; - - decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT; - - std::array buff{}; - while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) { - char* next_out = buff.data(); - size_t avail_out = buff.size(); - - decoder_r = BrotliDecoderDecompressStream( - decoder_s, &avail_in, &next_in, &avail_out, - reinterpret_cast(&next_out), &total_out); - - if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { - return false; - } - - if (!callback(buff.data(), buff.size() - avail_out)) { - return false; - } - } - - return decoder_r == BROTLI_DECODER_RESULT_SUCCESS || - decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT; - } -#endif - -#ifdef CPPHTTPLIB_ZSTD_SUPPORT - inline zstd_compressor::zstd_compressor() { - ctx_ = ZSTD_createCCtx(); - ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast); - } - - inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); } - - inline bool zstd_compressor::compress(const char* data, size_t data_length, bool last, - Callback callback) { - std::array buff{}; - - ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue; - ZSTD_inBuffer input = {data, data_length, 0}; - - bool finished; - do { - ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0}; - size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode); - - if (ZSTD_isError(remaining)) { - return false; - } - - if (!callback(buff.data(), output.pos)) { - return false; - } - - finished = last ? (remaining == 0) : (input.pos == input.size); - - } while (!finished); - - return true; - } - - inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); } - - inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); } - - inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; } - - inline bool zstd_decompressor::decompress(const char* data, size_t data_length, - Callback callback) { - std::array buff{}; - ZSTD_inBuffer input = {data, data_length, 0}; - - while (input.pos < input.size) { - ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0}; - size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input); - - if (ZSTD_isError(remaining)) { - return false; - } - - if (!callback(buff.data(), output.pos)) { - return false; - } - } - - return true; - } -#endif - - inline bool is_prohibited_header_name(const std::string& name) { - using udl::operator""_t; - - switch (str2tag(name)) { - case "REMOTE_ADDR"_t: - case "REMOTE_PORT"_t: - case "LOCAL_ADDR"_t: - case "LOCAL_PORT"_t: - return true; - default: - return false; - } - } - - inline bool has_header(const Headers& headers, const std::string& key) { - if (is_prohibited_header_name(key)) { - return false; - } - return headers.find(key) != headers.end(); - } - - inline const char* get_header_value(const Headers& headers, const std::string& key, - const char* def, size_t id) { - if (is_prohibited_header_name(key)) { -#ifndef CPPHTTPLIB_NO_EXCEPTIONS - std::string msg = "Prohibited header name '" + key + "' is specified."; - throw std::invalid_argument(msg); -#else - return ""; -#endif - } - - auto rng = headers.equal_range(key); - auto it = rng.first; - std::advance(it, static_cast(id)); - if (it != rng.second) { - return it->second.c_str(); - } - return def; - } - - template - inline bool parse_header(const char* beg, const char* end, T fn) { - // Skip trailing spaces and tabs. - while (beg < end && is_space_or_tab(end[-1])) { - end--; - } - - auto p = beg; - while (p < end && *p != ':') { - p++; - } - - auto name = std::string(beg, p); - if (!detail::fields::is_field_name(name)) { - return false; - } - - if (p == end) { - return false; - } - - auto key_end = p; - - if (*p++ != ':') { - return false; - } - - while (p < end && is_space_or_tab(*p)) { - p++; - } - - if (p <= end) { - auto key_len = key_end - beg; - if (!key_len) { - return false; - } - - auto key = std::string(beg, key_end); - auto val = std::string(p, end); - - if (!detail::fields::is_field_value(val)) { - return false; - } - - if (case_ignore::equal(key, "Location") || case_ignore::equal(key, "Referer")) { - fn(key, val); - } else { - fn(key, decode_path_component(val)); - } - - return true; - } - - return false; - } - - inline bool read_headers(Stream& strm, Headers& headers) { - const auto bufsiz = 2048; - char buf[bufsiz]; - stream_line_reader line_reader(strm, buf, bufsiz); - - size_t header_count = 0; - - for (;;) { - if (!line_reader.getline()) { - return false; - } - - // Check if the line ends with CRLF. - auto line_terminator_len = 2; - if (line_reader.end_with_crlf()) { - // Blank line indicates end of headers. - if (line_reader.size() == 2) { - break; - } - } else { -#ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR - // Blank line indicates end of headers. - if (line_reader.size() == 1) { - break; - } - line_terminator_len = 1; -#else - continue; // Skip invalid line. -#endif - } - - if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { - return false; - } - - // Check header count limit - if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { - return false; - } - - // Exclude line terminator - auto end = line_reader.ptr() + line_reader.size() - line_terminator_len; - - if (!parse_header(line_reader.ptr(), end, - [&](const std::string& key, const std::string& val) { - headers.emplace(key, val); - })) { - return false; - } - - header_count++; - } - - return true; - } - - inline bool read_content_with_length(Stream& strm, size_t len, DownloadProgress progress, - ContentReceiverWithProgress out) { - char buf[CPPHTTPLIB_RECV_BUFSIZ]; - - size_t r = 0; - while (r < len) { - auto read_len = static_cast(len - r); - auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ)); - if (n <= 0) { - return false; - } - - if (!out(buf, static_cast(n), r, len)) { - return false; - } - r += static_cast(n); - - if (progress) { - if (!progress(r, len)) { - return false; - } - } - } - - return true; - } - - inline void skip_content_with_length(Stream& strm, size_t len) { - char buf[CPPHTTPLIB_RECV_BUFSIZ]; - size_t r = 0; - while (r < len) { - auto read_len = static_cast(len - r); - auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ)); - if (n <= 0) { - return; - } - r += static_cast(n); - } - } - - enum class ReadContentResult { - Success, // Successfully read the content - PayloadTooLarge, // The content exceeds the specified payload limit - Error // An error occurred while reading the content - }; - - inline ReadContentResult read_content_without_length(Stream& strm, - size_t payload_max_length, - ContentReceiverWithProgress out) { - char buf[CPPHTTPLIB_RECV_BUFSIZ]; - size_t r = 0; - for (;;) { - auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ); - if (n == 0) { - return ReadContentResult::Success; - } - if (n < 0) { - return ReadContentResult::Error; - } - - // Check if adding this data would exceed the payload limit - if (r > payload_max_length || payload_max_length - r < static_cast(n)) { - return ReadContentResult::PayloadTooLarge; - } - - if (!out(buf, static_cast(n), r, 0)) { - return ReadContentResult::Error; - } - r += static_cast(n); - } - - return ReadContentResult::Success; - } - - template - inline ReadContentResult read_content_chunked(Stream& strm, T& x, size_t payload_max_length, - ContentReceiverWithProgress out) { - const auto bufsiz = 16; - char buf[bufsiz]; - - stream_line_reader line_reader(strm, buf, bufsiz); - - if (!line_reader.getline()) { - return ReadContentResult::Error; - } - - unsigned long chunk_len; - size_t total_len = 0; - while (true) { - char* end_ptr; - - chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16); - - if (end_ptr == line_reader.ptr()) { - return ReadContentResult::Error; - } - if (chunk_len == ULONG_MAX) { - return ReadContentResult::Error; - } - - if (chunk_len == 0) { - break; - } - - // Check if adding this chunk would exceed the payload limit - if (total_len > payload_max_length || payload_max_length - total_len < chunk_len) { - return ReadContentResult::PayloadTooLarge; - } - - total_len += chunk_len; - - if (!read_content_with_length(strm, chunk_len, nullptr, out)) { - return ReadContentResult::Error; - } - - if (!line_reader.getline()) { - return ReadContentResult::Error; - } - - if (strcmp(line_reader.ptr(), "\r\n") != 0) { - return ReadContentResult::Error; - } - - if (!line_reader.getline()) { - return ReadContentResult::Error; - } - } - - assert(chunk_len == 0); - - // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked - // transfer coding is complete when a chunk with a chunk-size of zero is - // received, possibly followed by a trailer section, and finally terminated by - // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1 - // - // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section - // does't care for the existence of the final CRLF. In other words, it seems - // to be ok whether the final CRLF exists or not in the chunked data. - // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3 - // - // According to the reference code in RFC 9112, cpp-httplib now allows - // chunked transfer coding data without the final CRLF. - if (!line_reader.getline()) { - return ReadContentResult::Success; - } - - // RFC 7230 Section 4.1.2 - Headers prohibited in trailers - thread_local case_ignore::unordered_set prohibited_trailers = { - // Message framing - "transfer-encoding", "content-length", - - // Routing - "host", - - // Authentication - "authorization", "www-authenticate", "proxy-authenticate", "proxy-authorization", - "cookie", "set-cookie", - - // Request modifiers - "cache-control", "expect", "max-forwards", "pragma", "range", "te", - - // Response control - "age", "expires", "date", "location", "retry-after", "vary", "warning", - - // Payload processing - "content-encoding", "content-type", "content-range", "trailer"}; - - // Parse declared trailer headers once for performance - case_ignore::unordered_set declared_trailers; - if (has_header(x.headers, "Trailer")) { - auto trailer_header = get_header_value(x.headers, "Trailer", "", 0); - auto len = std::strlen(trailer_header); - - split(trailer_header, trailer_header + len, ',', [&](const char* b, const char* e) { - std::string key(b, e); - if (prohibited_trailers.find(key) == prohibited_trailers.end()) { - declared_trailers.insert(key); - } - }); - } - - size_t trailer_header_count = 0; - while (strcmp(line_reader.ptr(), "\r\n") != 0) { - if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { - return ReadContentResult::Error; - } - - // Check trailer header count limit - if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { - return ReadContentResult::Error; - } - - // Exclude line terminator - constexpr auto line_terminator_len = 2; - auto end = line_reader.ptr() + line_reader.size() - line_terminator_len; - - parse_header(line_reader.ptr(), end, - [&](const std::string& key, const std::string& val) { - if (declared_trailers.find(key) != declared_trailers.end()) { - x.trailers.emplace(key, val); - trailer_header_count++; - } - }); - - if (!line_reader.getline()) { - return ReadContentResult::Error; - } - } - - return ReadContentResult::Success; - } - - inline bool is_chunked_transfer_encoding(const Headers& headers) { - return case_ignore::equal(get_header_value(headers, "Transfer-Encoding", "", 0), - "chunked"); - } - - template - bool prepare_content_receiver(T& x, int& status, ContentReceiverWithProgress receiver, - bool decompress, U callback) { - if (decompress) { - std::string encoding = x.get_header_value("Content-Encoding"); - std::unique_ptr decompressor; - - if (encoding == "gzip" || encoding == "deflate") { -#ifdef CPPHTTPLIB_ZLIB_SUPPORT - decompressor = detail::make_unique(); -#else - status = StatusCode::UnsupportedMediaType_415; - return false; -#endif - } else if (encoding.find("br") != std::string::npos) { -#ifdef CPPHTTPLIB_BROTLI_SUPPORT - decompressor = detail::make_unique(); -#else - status = StatusCode::UnsupportedMediaType_415; - return false; -#endif - } else if (encoding == "zstd") { -#ifdef CPPHTTPLIB_ZSTD_SUPPORT - decompressor = detail::make_unique(); -#else - status = StatusCode::UnsupportedMediaType_415; - return false; -#endif - } - - if (decompressor) { - if (decompressor->is_valid()) { - ContentReceiverWithProgress out = [&](const char* buf, size_t n, size_t off, - size_t len) { - return decompressor->decompress(buf, n, - [&](const char* buf2, size_t n2) { - return receiver(buf2, n2, off, len); - }); - }; - return callback(std::move(out)); - } else { - status = StatusCode::InternalServerError_500; - return false; - } - } - } - - ContentReceiverWithProgress out = [&](const char* buf, size_t n, size_t off, - size_t len) { - return receiver(buf, n, off, len); - }; - return callback(std::move(out)); - } - - template - bool read_content(Stream& strm, T& x, size_t payload_max_length, int& status, - DownloadProgress progress, ContentReceiverWithProgress receiver, - bool decompress) { - return prepare_content_receiver( - x, status, std::move(receiver), decompress, - [&](const ContentReceiverWithProgress& out) { - auto ret = true; - auto exceed_payload_max_length = false; - - if (is_chunked_transfer_encoding(x.headers)) { - auto result = read_content_chunked(strm, x, payload_max_length, out); - if (result == ReadContentResult::Success) { - ret = true; - } else if (result == ReadContentResult::PayloadTooLarge) { - exceed_payload_max_length = true; - ret = false; - } else { - ret = false; - } - } else if (!has_header(x.headers, "Content-Length")) { - auto result = read_content_without_length(strm, payload_max_length, out); - if (result == ReadContentResult::Success) { - ret = true; - } else if (result == ReadContentResult::PayloadTooLarge) { - exceed_payload_max_length = true; - ret = false; - } else { - ret = false; - } - } else { - auto is_invalid_value = false; - auto len = get_header_value_u64(x.headers, "Content-Length", - (std::numeric_limits::max)(), 0, - is_invalid_value); - - if (is_invalid_value) { - ret = false; - } else if (len > payload_max_length) { - exceed_payload_max_length = true; - skip_content_with_length(strm, len); - ret = false; - } else if (len > 0) { - ret = read_content_with_length(strm, len, std::move(progress), out); - } - } - - if (!ret) { - status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413 - : StatusCode::BadRequest_400; - } - return ret; - }); - } - - inline ssize_t write_request_line(Stream& strm, const std::string& method, - const std::string& path) { - std::string s = method; - s += " "; - s += path; - s += " HTTP/1.1\r\n"; - return strm.write(s.data(), s.size()); - } - - inline ssize_t write_response_line(Stream& strm, int status) { - std::string s = "HTTP/1.1 "; - s += std::to_string(status); - s += " "; - s += httplib::status_message(status); - s += "\r\n"; - return strm.write(s.data(), s.size()); - } - - inline ssize_t write_headers(Stream& strm, const Headers& headers) { - ssize_t write_len = 0; - for (const auto& x : headers) { - std::string s; - s = x.first; - s += ": "; - s += x.second; - s += "\r\n"; - - auto len = strm.write(s.data(), s.size()); - if (len < 0) { - return len; - } - write_len += len; - } - auto len = strm.write("\r\n"); - if (len < 0) { - return len; - } - write_len += len; - return write_len; - } - - inline bool write_data(Stream& strm, const char* d, size_t l) { - size_t offset = 0; - while (offset < l) { - auto length = strm.write(d + offset, l - offset); - if (length < 0) { - return false; - } - offset += static_cast(length); - } - return true; - } - - template - inline bool write_content_with_progress(Stream& strm, - const ContentProvider& content_provider, - size_t offset, size_t length, T is_shutting_down, - const UploadProgress& upload_progress, - Error& error) { - size_t end_offset = offset + length; - size_t start_offset = offset; - auto ok = true; - DataSink data_sink; - - data_sink.write = [&](const char* d, size_t l) -> bool { - if (ok) { - if (write_data(strm, d, l)) { - offset += l; - - if (upload_progress && length > 0) { - size_t current_written = offset - start_offset; - if (!upload_progress(current_written, length)) { - ok = false; - return false; - } - } - } else { - ok = false; - } - } - return ok; - }; - - data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); }; - - while (offset < end_offset && !is_shutting_down()) { - if (!strm.wait_writable()) { - error = Error::Write; - return false; - } else if (!content_provider(offset, end_offset - offset, data_sink)) { - error = Error::Canceled; - return false; - } else if (!ok) { - error = Error::Write; - return false; - } - } - - error = Error::Success; - return true; - } - - template - inline bool write_content(Stream& strm, const ContentProvider& content_provider, - size_t offset, size_t length, T is_shutting_down, Error& error) { - return write_content_with_progress(strm, content_provider, offset, length, - is_shutting_down, nullptr, error); - } - - template - inline bool write_content(Stream& strm, const ContentProvider& content_provider, - size_t offset, size_t length, const T& is_shutting_down) { - auto error = Error::Success; - return write_content(strm, content_provider, offset, length, is_shutting_down, error); - } - - template - inline bool write_content_without_length(Stream& strm, - const ContentProvider& content_provider, - const T& is_shutting_down) { - size_t offset = 0; - auto data_available = true; - auto ok = true; - DataSink data_sink; - - data_sink.write = [&](const char* d, size_t l) -> bool { - if (ok) { - offset += l; - if (!write_data(strm, d, l)) { - ok = false; - } - } - return ok; - }; - - data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); }; - - data_sink.done = [&](void) { data_available = false; }; - - while (data_available && !is_shutting_down()) { - if (!strm.wait_writable()) { - return false; - } else if (!content_provider(offset, 0, data_sink)) { - return false; - } else if (!ok) { - return false; - } - } - return true; - } - - template - inline bool write_content_chunked(Stream& strm, const ContentProvider& content_provider, - const T& is_shutting_down, U& compressor, Error& error) { - size_t offset = 0; - auto data_available = true; - auto ok = true; - DataSink data_sink; - - data_sink.write = [&](const char* d, size_t l) -> bool { - if (ok) { - data_available = l > 0; - offset += l; - - std::string payload; - if (compressor.compress(d, l, false, [&](const char* data, size_t data_len) { - payload.append(data, data_len); - return true; - })) { - if (!payload.empty()) { - // Emit chunked response header and footer for each chunk - auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n"; - if (!write_data(strm, chunk.data(), chunk.size())) { - ok = false; - } - } - } else { - ok = false; - } - } - return ok; - }; - - data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); }; - - auto done_with_trailer = [&](const Headers* trailer) { - if (!ok) { - return; - } - - data_available = false; - - std::string payload; - if (!compressor.compress(nullptr, 0, true, [&](const char* data, size_t data_len) { - payload.append(data, data_len); - return true; - })) { - ok = false; - return; - } - - if (!payload.empty()) { - // Emit chunked response header and footer for each chunk - auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n"; - if (!write_data(strm, chunk.data(), chunk.size())) { - ok = false; - return; - } - } - - constexpr const char done_marker[] = "0\r\n"; - if (!write_data(strm, done_marker, str_len(done_marker))) { - ok = false; - } - - // Trailer - if (trailer) { - for (const auto& kv : *trailer) { - std::string field_line = kv.first + ": " + kv.second + "\r\n"; - if (!write_data(strm, field_line.data(), field_line.size())) { - ok = false; - } - } - } - - constexpr const char crlf[] = "\r\n"; - if (!write_data(strm, crlf, str_len(crlf))) { - ok = false; - } - }; - - data_sink.done = [&](void) { done_with_trailer(nullptr); }; - - data_sink.done_with_trailer = [&](const Headers& trailer) { - done_with_trailer(&trailer); - }; - - while (data_available && !is_shutting_down()) { - if (!strm.wait_writable()) { - error = Error::Write; - return false; - } else if (!content_provider(offset, 0, data_sink)) { - error = Error::Canceled; - return false; - } else if (!ok) { - error = Error::Write; - return false; - } - } - - error = Error::Success; - return true; - } - - template - inline bool write_content_chunked(Stream& strm, const ContentProvider& content_provider, - const T& is_shutting_down, U& compressor) { - auto error = Error::Success; - return write_content_chunked(strm, content_provider, is_shutting_down, compressor, - error); - } - - template - inline bool redirect(T& cli, Request& req, Response& res, const std::string& path, - const std::string& location, Error& error) { - Request new_req = req; - new_req.path = path; - new_req.redirect_count_ -= 1; - - if (res.status == StatusCode::SeeOther_303 && - (req.method != "GET" && req.method != "HEAD")) { - new_req.method = "GET"; - new_req.body.clear(); - new_req.headers.clear(); - } - - Response new_res; - - auto ret = cli.send(new_req, new_res, error); - if (ret) { - req = new_req; - res = new_res; - - if (res.location.empty()) { - res.location = location; - } - } - return ret; - } - - inline std::string params_to_query_str(const Params& params) { - std::string query; - - for (auto it = params.begin(); it != params.end(); ++it) { - if (it != params.begin()) { - query += "&"; - } - query += encode_query_component(it->first); - query += "="; - query += encode_query_component(it->second); - } - return query; - } - - inline void parse_query_text(const char* data, std::size_t size, Params& params) { - std::set cache; - split(data, data + size, '&', [&](const char* b, const char* e) { - std::string kv(b, e); - if (cache.find(kv) != cache.end()) { - return; - } - cache.insert(std::move(kv)); - - std::string key; - std::string val; - divide(b, static_cast(e - b), '=', - [&](const char* lhs_data, std::size_t lhs_size, const char* rhs_data, - std::size_t rhs_size) { - key.assign(lhs_data, lhs_size); - val.assign(rhs_data, rhs_size); - }); - - if (!key.empty()) { - params.emplace(decode_query_component(key), decode_query_component(val)); - } - }); - } - - inline void parse_query_text(const std::string& s, Params& params) { - parse_query_text(s.data(), s.size(), params); - } - - inline bool parse_multipart_boundary(const std::string& content_type, - std::string& boundary) { - auto boundary_keyword = "boundary="; - auto pos = content_type.find(boundary_keyword); - if (pos == std::string::npos) { - return false; - } - auto end = content_type.find(';', pos); - auto beg = pos + strlen(boundary_keyword); - boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg)); - return !boundary.empty(); - } - - inline void parse_disposition_params(const std::string& s, Params& params) { - std::set cache; - split(s.data(), s.data() + s.size(), ';', [&](const char* b, const char* e) { - std::string kv(b, e); - if (cache.find(kv) != cache.end()) { - return; - } - cache.insert(kv); - - std::string key; - std::string val; - split(b, e, '=', [&](const char* b2, const char* e2) { - if (key.empty()) { - key.assign(b2, e2); - } else { - val.assign(b2, e2); - } - }); - - if (!key.empty()) { - params.emplace(trim_double_quotes_copy((key)), trim_double_quotes_copy((val))); - } - }); - } - -#ifdef CPPHTTPLIB_NO_EXCEPTIONS - inline bool parse_range_header(const std::string& s, Ranges& ranges) { -#else - inline bool parse_range_header(const std::string& s, Ranges& ranges) try { -#endif - auto is_valid = [](const std::string& str) { - return std::all_of(str.cbegin(), str.cend(), - [](unsigned char c) { return std::isdigit(c); }); - }; - - if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) { - const auto pos = static_cast(6); - const auto len = static_cast(s.size() - 6); - auto all_valid_ranges = true; - split(&s[pos], &s[pos + len], ',', [&](const char* b, const char* e) { - if (!all_valid_ranges) { - return; - } - - const auto it = std::find(b, e, '-'); - if (it == e) { - all_valid_ranges = false; - return; - } - - const auto lhs = std::string(b, it); - const auto rhs = std::string(it + 1, e); - if (!is_valid(lhs) || !is_valid(rhs)) { - all_valid_ranges = false; - return; - } - - const auto first = static_cast(lhs.empty() ? -1 : std::stoll(lhs)); - const auto last = static_cast(rhs.empty() ? -1 : std::stoll(rhs)); - if ((first == -1 && last == -1) || - (first != -1 && last != -1 && first > last)) { - all_valid_ranges = false; - return; - } - - ranges.emplace_back(first, last); - }); - return all_valid_ranges && !ranges.empty(); - } - return false; -#ifdef CPPHTTPLIB_NO_EXCEPTIONS - } -#else - } catch (...) { - return false; - } -#endif - - inline bool parse_accept_header(const std::string& s, - std::vector& content_types) { - content_types.clear(); - - // Empty string is considered valid (no preference) - if (s.empty()) { - return true; - } - - // Check for invalid patterns: leading/trailing commas or consecutive commas - if (s.front() == ',' || s.back() == ',' || s.find(",,") != std::string::npos) { - return false; - } - - struct AcceptEntry { - std::string media_type; - double quality; - int order; // Original order in header - }; - - std::vector entries; - int order = 0; - bool has_invalid_entry = false; - - // Split by comma and parse each entry - split(s.data(), s.data() + s.size(), ',', [&](const char* b, const char* e) { - std::string entry(b, e); - entry = trim_copy(entry); - - if (entry.empty()) { - has_invalid_entry = true; - return; - } - - AcceptEntry accept_entry; - accept_entry.quality = 1.0; // Default quality - accept_entry.order = order++; - - // Find q= parameter - auto q_pos = entry.find(";q="); - if (q_pos == std::string::npos) { - q_pos = entry.find("; q="); - } - - if (q_pos != std::string::npos) { - // Extract media type (before q parameter) - accept_entry.media_type = trim_copy(entry.substr(0, q_pos)); - - // Extract quality value - auto q_start = entry.find('=', q_pos) + 1; - auto q_end = entry.find(';', q_start); - if (q_end == std::string::npos) { - q_end = entry.length(); - } - - std::string quality_str = trim_copy(entry.substr(q_start, q_end - q_start)); - if (quality_str.empty()) { - has_invalid_entry = true; - return; - } - -#ifdef CPPHTTPLIB_NO_EXCEPTIONS - { - std::istringstream iss(quality_str); - iss >> accept_entry.quality; - - // Check if conversion was successful and entire string was consumed - if (iss.fail() || !iss.eof()) { - has_invalid_entry = true; - return; - } - } -#else - try { - accept_entry.quality = std::stod(quality_str); - } catch (...) { - has_invalid_entry = true; - return; - } -#endif - // Check if quality is in valid range [0.0, 1.0] - if (accept_entry.quality < 0.0 || accept_entry.quality > 1.0) { - has_invalid_entry = true; - return; - } - } else { - // No quality parameter, use entire entry as media type - accept_entry.media_type = entry; - } - - // Remove additional parameters from media type - auto param_pos = accept_entry.media_type.find(';'); - if (param_pos != std::string::npos) { - accept_entry.media_type = - trim_copy(accept_entry.media_type.substr(0, param_pos)); - } - - // Basic validation of media type format - if (accept_entry.media_type.empty()) { - has_invalid_entry = true; - return; - } - - // Check for basic media type format (should contain '/' or be '*') - if (accept_entry.media_type != "*" && - accept_entry.media_type.find('/') == std::string::npos) { - has_invalid_entry = true; - return; - } - - entries.push_back(accept_entry); - }); - - // Return false if any invalid entry was found - if (has_invalid_entry) { - return false; - } - - // Sort by quality (descending), then by original order (ascending) - std::sort(entries.begin(), entries.end(), - [](const AcceptEntry& a, const AcceptEntry& b) { - if (a.quality != b.quality) { - return a.quality > b.quality; // Higher quality first - } - return a.order < b.order; // Earlier order first for same quality - }); - - // Extract sorted media types - content_types.reserve(entries.size()); - for (const auto& entry : entries) { - content_types.push_back(entry.media_type); - } - - return true; - } - - class FormDataParser { - public: - FormDataParser() = default; - - void set_boundary(std::string&& boundary) { - boundary_ = boundary; - dash_boundary_crlf_ = dash_ + boundary_ + crlf_; - crlf_dash_boundary_ = crlf_ + dash_ + boundary_; - } - - bool is_valid() const { return is_valid_; } - - bool parse(const char* buf, size_t n, const FormDataHeader& header_callback, - const ContentReceiver& content_callback) { - buf_append(buf, n); - - while (buf_size() > 0) { - switch (state_) { - case 0: { // Initial boundary - auto pos = buf_find(dash_boundary_crlf_); - if (pos == buf_size()) { - return true; - } - buf_erase(pos + dash_boundary_crlf_.size()); - state_ = 1; - break; - } - case 1: { // New entry - clear_file_info(); - state_ = 2; - break; - } - case 2: { // Headers - auto pos = buf_find(crlf_); - if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { - return false; - } - while (pos < buf_size()) { - // Empty line - if (pos == 0) { - if (!header_callback(file_)) { - is_valid_ = false; - return false; - } - buf_erase(crlf_.size()); - state_ = 3; - break; - } - - const auto header = buf_head(pos); - - if (!parse_header(header.data(), header.data() + header.size(), - [&](const std::string&, const std::string&) {})) { - is_valid_ = false; - return false; - } - - // Parse and emplace space trimmed headers into a map - if (!parse_header( - header.data(), header.data() + header.size(), - [&](const std::string& key, const std::string& val) { - file_.headers.emplace(key, val); - })) { - is_valid_ = false; - return false; - } - - constexpr const char header_content_type[] = "Content-Type:"; - - if (start_with_case_ignore(header, header_content_type)) { - file_.content_type = - trim_copy(header.substr(str_len(header_content_type))); - } else { - thread_local const std::regex re_content_disposition( - R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~", - std::regex_constants::icase); - - std::smatch m; - if (std::regex_match(header, m, re_content_disposition)) { - Params params; - parse_disposition_params(m[1], params); - - auto it = params.find("name"); - if (it != params.end()) { - file_.name = it->second; - } else { - is_valid_ = false; - return false; - } - - it = params.find("filename"); - if (it != params.end()) { - file_.filename = it->second; - } - - it = params.find("filename*"); - if (it != params.end()) { - // Only allow UTF-8 encoding... - thread_local const std::regex re_rfc5987_encoding( - R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase); - - std::smatch m2; - if (std::regex_match(it->second, m2, - re_rfc5987_encoding)) { - file_.filename = - decode_path_component(m2[1]); // override... - } else { - is_valid_ = false; - return false; - } - } - } - } - buf_erase(pos + crlf_.size()); - pos = buf_find(crlf_); - } - if (state_ != 3) { - return true; - } - break; - } - case 3: { // Body - if (crlf_dash_boundary_.size() > buf_size()) { - return true; - } - auto pos = buf_find(crlf_dash_boundary_); - if (pos < buf_size()) { - if (!content_callback(buf_data(), pos)) { - is_valid_ = false; - return false; - } - buf_erase(pos + crlf_dash_boundary_.size()); - state_ = 4; - } else { - auto len = buf_size() - crlf_dash_boundary_.size(); - if (len > 0) { - if (!content_callback(buf_data(), len)) { - is_valid_ = false; - return false; - } - buf_erase(len); - } - return true; - } - break; - } - case 4: { // Boundary - if (crlf_.size() > buf_size()) { - return true; - } - if (buf_start_with(crlf_)) { - buf_erase(crlf_.size()); - state_ = 1; - } else { - if (dash_.size() > buf_size()) { - return true; - } - if (buf_start_with(dash_)) { - buf_erase(dash_.size()); - is_valid_ = true; - buf_erase(buf_size()); // Remove epilogue - } else { - return true; - } - } - break; - } - } - } - - return true; - } - - private: - void clear_file_info() { - file_.name.clear(); - file_.filename.clear(); - file_.content_type.clear(); - file_.headers.clear(); - } - - bool start_with_case_ignore(const std::string& a, const char* b) const { - const auto b_len = strlen(b); - if (a.size() < b_len) { - return false; - } - for (size_t i = 0; i < b_len; i++) { - if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) { - return false; - } - } - return true; - } - - const std::string dash_ = "--"; - const std::string crlf_ = "\r\n"; - std::string boundary_; - std::string dash_boundary_crlf_; - std::string crlf_dash_boundary_; - - size_t state_ = 0; - bool is_valid_ = false; - FormData file_; - - // Buffer - bool start_with(const std::string& a, size_t spos, size_t epos, - const std::string& b) const { - if (epos - spos < b.size()) { - return false; - } - for (size_t i = 0; i < b.size(); i++) { - if (a[i + spos] != b[i]) { - return false; - } - } - return true; - } - - size_t buf_size() const { return buf_epos_ - buf_spos_; } - - const char* buf_data() const { return &buf_[buf_spos_]; } - - std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); } - - bool buf_start_with(const std::string& s) const { - return start_with(buf_, buf_spos_, buf_epos_, s); - } - - size_t buf_find(const std::string& s) const { - auto c = s.front(); - - size_t off = buf_spos_; - while (off < buf_epos_) { - auto pos = off; - while (true) { - if (pos == buf_epos_) { - return buf_size(); - } - if (buf_[pos] == c) { - break; - } - pos++; - } - - auto remaining_size = buf_epos_ - pos; - if (s.size() > remaining_size) { - return buf_size(); - } - - if (start_with(buf_, pos, buf_epos_, s)) { - return pos - buf_spos_; - } - - off = pos + 1; - } - - return buf_size(); - } - - void buf_append(const char* data, size_t n) { - auto remaining_size = buf_size(); - if (remaining_size > 0 && buf_spos_ > 0) { - for (size_t i = 0; i < remaining_size; i++) { - buf_[i] = buf_[buf_spos_ + i]; - } - } - buf_spos_ = 0; - buf_epos_ = remaining_size; - - if (remaining_size + n > buf_.size()) { - buf_.resize(remaining_size + n); - } - - for (size_t i = 0; i < n; i++) { - buf_[buf_epos_ + i] = data[i]; - } - buf_epos_ += n; - } - - void buf_erase(size_t size) { buf_spos_ += size; } - - std::string buf_; - size_t buf_spos_ = 0; - size_t buf_epos_ = 0; - }; - - inline std::string random_string(size_t length) { - constexpr const char data[] = - "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - - thread_local auto engine([]() { - // std::random_device might actually be deterministic on some - // platforms, but due to lack of support in the c++ standard library, - // doing better requires either some ugly hacks or breaking portability. - std::random_device seed_gen; - // Request 128 bits of entropy for initialization - std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()}; - return std::mt19937(seed_sequence); - }()); - - std::string result; - for (size_t i = 0; i < length; i++) { - result += data[engine() % (sizeof(data) - 1)]; - } - return result; - } - - inline std::string make_multipart_data_boundary() { - return "--cpp-httplib-multipart-data-" + detail::random_string(16); - } - - inline bool is_multipart_boundary_chars_valid(const std::string& boundary) { - auto valid = true; - for (size_t i = 0; i < boundary.size(); i++) { - auto c = boundary[i]; - if (!std::isalnum(c) && c != '-' && c != '_') { - valid = false; - break; - } - } - return valid; - } - - template - inline std::string serialize_multipart_formdata_item_begin(const T& item, - const std::string& boundary) { - std::string body = "--" + boundary + "\r\n"; - body += "Content-Disposition: form-data; name=\"" + item.name + "\""; - if (!item.filename.empty()) { - body += "; filename=\"" + item.filename + "\""; - } - body += "\r\n"; - if (!item.content_type.empty()) { - body += "Content-Type: " + item.content_type + "\r\n"; - } - body += "\r\n"; - - return body; - } - - inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; } - - inline std::string serialize_multipart_formdata_finish(const std::string& boundary) { - return "--" + boundary + "--\r\n"; - } - - inline std::string serialize_multipart_formdata_get_content_type( - const std::string& boundary) { - return "multipart/form-data; boundary=" + boundary; - } - - inline std::string serialize_multipart_formdata(const UploadFormDataItems& items, - const std::string& boundary, - bool finish = true) { - std::string body; - - for (const auto& item : items) { - body += serialize_multipart_formdata_item_begin(item, boundary); - body += item.content + serialize_multipart_formdata_item_end(); - } - - if (finish) { - body += serialize_multipart_formdata_finish(boundary); - } - - return body; - } - - inline void coalesce_ranges(Ranges& ranges, size_t content_length) { - if (ranges.size() <= 1) - return; - - // Sort ranges by start position - std::sort(ranges.begin(), ranges.end(), - [](const Range& a, const Range& b) { return a.first < b.first; }); - - Ranges coalesced; - coalesced.reserve(ranges.size()); - - for (auto& r : ranges) { - auto first_pos = r.first; - auto last_pos = r.second; - - // Handle special cases like in range_error - if (first_pos == -1 && last_pos == -1) { - first_pos = 0; - last_pos = static_cast(content_length); - } - - if (first_pos == -1) { - first_pos = static_cast(content_length) - last_pos; - last_pos = static_cast(content_length) - 1; - } - - if (last_pos == -1 || last_pos >= static_cast(content_length)) { - last_pos = static_cast(content_length) - 1; - } - - // Skip invalid ranges - if (!(0 <= first_pos && first_pos <= last_pos && - last_pos < static_cast(content_length))) { - continue; - } - - // Coalesce with previous range if overlapping or adjacent (but not - // identical) - if (!coalesced.empty()) { - auto& prev = coalesced.back(); - // Check if current range overlaps or is adjacent to previous range - // but don't coalesce identical ranges (allow duplicates) - if (first_pos <= prev.second + 1 && - !(first_pos == prev.first && last_pos == prev.second)) { - // Extend the previous range - prev.second = (std::max)(prev.second, last_pos); - continue; - } - } - - // Add new range - coalesced.emplace_back(first_pos, last_pos); - } - - ranges = std::move(coalesced); - } - - inline bool range_error(Request& req, Response& res) { - if (!req.ranges.empty() && 200 <= res.status && res.status < 300) { - ssize_t content_len = static_cast(res.content_length_ ? res.content_length_ - : res.body.size()); - - std::vector> processed_ranges; - size_t overwrapping_count = 0; - - // NOTE: The following Range check is based on '14.2. Range' in RFC 9110 - // 'HTTP Semantics' to avoid potential denial-of-service attacks. - // https://www.rfc-editor.org/rfc/rfc9110#section-14.2 - - // Too many ranges - if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { - return true; - } - - for (auto& r : req.ranges) { - auto& first_pos = r.first; - auto& last_pos = r.second; - - if (first_pos == -1 && last_pos == -1) { - first_pos = 0; - last_pos = content_len; - } - - if (first_pos == -1) { - first_pos = content_len - last_pos; - last_pos = content_len - 1; - } - - // NOTE: RFC-9110 '14.1.2. Byte Ranges': - // A client can limit the number of bytes requested without knowing the - // size of the selected representation. If the last-pos value is absent, - // or if the value is greater than or equal to the current length of the - // representation data, the byte range is interpreted as the remainder of - // the representation (i.e., the server replaces the value of last-pos - // with a value that is one less than the current length of the selected - // representation). - // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6 - if (last_pos == -1 || last_pos >= content_len) { - last_pos = content_len - 1; - } - - // Range must be within content length - if (!(0 <= first_pos && first_pos <= last_pos && last_pos <= content_len - 1)) { - return true; - } - - // Request must not have more than two overlapping ranges - for (const auto& processed_range : processed_ranges) { - if (!(last_pos < processed_range.first || - first_pos > processed_range.second)) { - overwrapping_count++; - if (overwrapping_count > 2) { - return true; - } - break; // Only count once per range - } - } - - processed_ranges.emplace_back(first_pos, last_pos); - } - - // After validation, coalesce overlapping ranges as per RFC 9110 - coalesce_ranges(req.ranges, static_cast(content_len)); - } - - return false; - } - - inline std::pair get_range_offset_and_length(Range r, - size_t content_length) { - assert(r.first != -1 && r.second != -1); - assert(0 <= r.first && r.first < static_cast(content_length)); - assert(r.first <= r.second && r.second < static_cast(content_length)); - (void)(content_length); - return std::make_pair(r.first, static_cast(r.second - r.first) + 1); - } - - inline std::string make_content_range_header_field( - const std::pair& offset_and_length, size_t content_length) { - auto st = offset_and_length.first; - auto ed = st + offset_and_length.second - 1; - - std::string field = "bytes "; - field += std::to_string(st); - field += "-"; - field += std::to_string(ed); - field += "/"; - field += std::to_string(content_length); - return field; - } - - template - bool process_multipart_ranges_data(const Request& req, const std::string& boundary, - const std::string& content_type, size_t content_length, - SToken stoken, CToken ctoken, Content content) { - for (size_t i = 0; i < req.ranges.size(); i++) { - ctoken("--"); - stoken(boundary); - ctoken("\r\n"); - if (!content_type.empty()) { - ctoken("Content-Type: "); - stoken(content_type); - ctoken("\r\n"); - } - - auto offset_and_length = get_range_offset_and_length(req.ranges[i], content_length); - - ctoken("Content-Range: "); - stoken(make_content_range_header_field(offset_and_length, content_length)); - ctoken("\r\n"); - ctoken("\r\n"); - - if (!content(offset_and_length.first, offset_and_length.second)) { - return false; - } - ctoken("\r\n"); - } - - ctoken("--"); - stoken(boundary); - ctoken("--"); - - return true; - } - - inline void make_multipart_ranges_data(const Request& req, Response& res, - const std::string& boundary, - const std::string& content_type, - size_t content_length, std::string& data) { - process_multipart_ranges_data( - req, boundary, content_type, content_length, - [&](const std::string& token) { data += token; }, - [&](const std::string& token) { data += token; }, - [&](size_t offset, size_t length) { - assert(offset + length <= content_length); - data += res.body.substr(offset, length); - return true; - }); - } - - inline size_t get_multipart_ranges_data_length(const Request& req, - const std::string& boundary, - const std::string& content_type, - size_t content_length) { - size_t data_length = 0; - - process_multipart_ranges_data( - req, boundary, content_type, content_length, - [&](const std::string& token) { data_length += token.size(); }, - [&](const std::string& token) { data_length += token.size(); }, - [&](size_t /*offset*/, size_t length) { - data_length += length; - return true; - }); - - return data_length; - } - - template - inline bool write_multipart_ranges_data(Stream& strm, const Request& req, Response& res, - const std::string& boundary, - const std::string& content_type, - size_t content_length, const T& is_shutting_down) { - return process_multipart_ranges_data( - req, boundary, content_type, content_length, - [&](const std::string& token) { strm.write(token); }, - [&](const std::string& token) { strm.write(token); }, - [&](size_t offset, size_t length) { - return write_content(strm, res.content_provider_, offset, length, - is_shutting_down); - }); - } - - inline bool expect_content(const Request& req) { - if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" || - req.method == "DELETE") { - return true; - } - if (req.has_header("Content-Length") && - req.get_header_value_u64("Content-Length") > 0) { - return true; - } - if (is_chunked_transfer_encoding(req.headers)) { - return true; - } - return false; - } - - inline bool has_crlf(const std::string& s) { - auto p = s.c_str(); - while (*p) { - if (*p == '\r' || *p == '\n') { - return true; - } - p++; - } - return false; - } - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - inline std::string message_digest(const std::string& s, const EVP_MD* algo) { - auto context = std::unique_ptr(EVP_MD_CTX_new(), - EVP_MD_CTX_free); - - unsigned int hash_length = 0; - unsigned char hash[EVP_MAX_MD_SIZE]; - - EVP_DigestInit_ex(context.get(), algo, nullptr); - EVP_DigestUpdate(context.get(), s.c_str(), s.size()); - EVP_DigestFinal_ex(context.get(), hash, &hash_length); - - std::stringstream ss; - for (auto i = 0u; i < hash_length; ++i) { - ss << std::hex << std::setw(2) << std::setfill('0') - << static_cast(hash[i]); - } - - return ss.str(); - } - - inline std::string MD5(const std::string& s) { return message_digest(s, EVP_md5()); } - - inline std::string SHA_256(const std::string& s) { return message_digest(s, EVP_sha256()); } - - inline std::string SHA_512(const std::string& s) { return message_digest(s, EVP_sha512()); } - - inline std::pair make_digest_authentication_header( - const Request& req, const std::map& auth, size_t cnonce_count, - const std::string& cnonce, const std::string& username, const std::string& password, - bool is_proxy = false) { - std::string nc; - { - std::stringstream ss; - ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count; - nc = ss.str(); - } - - std::string qop; - if (auth.find("qop") != auth.end()) { - qop = auth.at("qop"); - if (qop.find("auth-int") != std::string::npos) { - qop = "auth-int"; - } else if (qop.find("auth") != std::string::npos) { - qop = "auth"; - } else { - qop.clear(); - } - } - - std::string algo = "MD5"; - if (auth.find("algorithm") != auth.end()) { - algo = auth.at("algorithm"); - } - - std::string response; - { - auto H = algo == "SHA-256" ? detail::SHA_256 - : algo == "SHA-512" ? detail::SHA_512 - : detail::MD5; - - auto A1 = username + ":" + auth.at("realm") + ":" + password; - - auto A2 = req.method + ":" + req.path; - if (qop == "auth-int") { - A2 += ":" + H(req.body); - } - - if (qop.empty()) { - response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2)); - } else { - response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce + ":" + - qop + ":" + H(A2)); - } - } - - auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : ""; - - auto field = "Digest username=\"" + username + "\", realm=\"" + auth.at("realm") + - "\", nonce=\"" + auth.at("nonce") + "\", uri=\"" + req.path + - "\", algorithm=" + algo + - (qop.empty() ? ", response=\"" - : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" + cnonce + - "\", response=\"") + - response + "\"" + (opaque.empty() ? "" : ", opaque=\"" + opaque + "\""); - - auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; - return std::make_pair(key, field); - } - - inline bool is_ssl_peer_could_be_closed(SSL* ssl, socket_t sock) { - detail::set_nonblocking(sock, true); - auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); }); - - char buf[1]; - return !SSL_peek(ssl, buf, 1) && SSL_get_error(ssl, 0) == SSL_ERROR_ZERO_RETURN; - } - -#ifdef _WIN32 - // NOTE: This code came up with the following stackoverflow post: - // https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store - inline bool load_system_certs_on_windows(X509_STORE* store) { - auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT"); - if (!hStore) { - return false; - } - - auto result = false; - PCCERT_CONTEXT pContext = NULL; - while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) != nullptr) { - auto encoded_cert = static_cast(pContext->pbCertEncoded); - - auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded); - if (x509) { - X509_STORE_add_cert(store, x509); - X509_free(x509); - result = true; - } - } - - CertFreeCertificateContext(pContext); - CertCloseStore(hStore, 0); - - return result; - } -#elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && TARGET_OS_MAC - template - using CFObjectPtr = - std::unique_ptr::type, void (*)(CFTypeRef)>; - - inline void cf_object_ptr_deleter(CFTypeRef obj) { - if (obj) { - CFRelease(obj); - } - } - - inline bool retrieve_certs_from_keychain(CFObjectPtr& certs) { - CFStringRef keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef}; - CFTypeRef values[] = {kSecClassCertificate, kSecMatchLimitAll, kCFBooleanTrue}; - - CFObjectPtr query( - CFDictionaryCreate(nullptr, reinterpret_cast(keys), values, - sizeof(keys) / sizeof(keys[0]), &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks), - cf_object_ptr_deleter); - - if (!query) { - return false; - } - - CFTypeRef security_items = nullptr; - if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess || - CFArrayGetTypeID() != CFGetTypeID(security_items)) { - return false; - } - - certs.reset(reinterpret_cast(security_items)); - return true; - } - - inline bool retrieve_root_certs_from_keychain(CFObjectPtr& certs) { - CFArrayRef root_security_items = nullptr; - if (SecTrustCopyAnchorCertificates(&root_security_items) != errSecSuccess) { - return false; - } - - certs.reset(root_security_items); - return true; - } - - inline bool add_certs_to_x509_store(CFArrayRef certs, X509_STORE* store) { - auto result = false; - for (auto i = 0; i < CFArrayGetCount(certs); ++i) { - const auto cert = - reinterpret_cast(CFArrayGetValueAtIndex(certs, i)); - - if (SecCertificateGetTypeID() != CFGetTypeID(cert)) { - continue; - } - - CFDataRef cert_data = nullptr; - if (SecItemExport(cert, kSecFormatX509Cert, 0, nullptr, &cert_data) != - errSecSuccess) { - continue; - } - - CFObjectPtr cert_data_ptr(cert_data, cf_object_ptr_deleter); - - auto encoded_cert = - static_cast(CFDataGetBytePtr(cert_data_ptr.get())); - - auto x509 = d2i_X509(NULL, &encoded_cert, CFDataGetLength(cert_data_ptr.get())); - - if (x509) { - X509_STORE_add_cert(store, x509); - X509_free(x509); - result = true; - } - } - - return result; - } - - inline bool load_system_certs_on_macos(X509_STORE* store) { - auto result = false; - CFObjectPtr certs(nullptr, cf_object_ptr_deleter); - if (retrieve_certs_from_keychain(certs) && certs) { - result = add_certs_to_x509_store(certs.get(), store); - } - - if (retrieve_root_certs_from_keychain(certs) && certs) { - result = add_certs_to_x509_store(certs.get(), store) || result; - } - - return result; - } -#endif // _WIN32 -#endif // CPPHTTPLIB_OPENSSL_SUPPORT - -#ifdef _WIN32 - class WSInit { - public: - WSInit() { - WSADATA wsaData; - if (WSAStartup(0x0002, &wsaData) == 0) - is_valid_ = true; - } - - ~WSInit() { - if (is_valid_) - WSACleanup(); - } - - bool is_valid_ = false; - }; - - static WSInit wsinit_; -#endif - - inline bool parse_www_authenticate(const Response& res, - std::map& auth, - bool is_proxy) { - auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate"; - if (res.has_header(auth_key)) { - thread_local auto re = std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~"); - auto s = res.get_header_value(auth_key); - auto pos = s.find(' '); - if (pos != std::string::npos) { - auto type = s.substr(0, pos); - if (type == "Basic") { - return false; - } else if (type == "Digest") { - s = s.substr(pos + 1); - auto beg = std::sregex_iterator(s.begin(), s.end(), re); - for (auto i = beg; i != std::sregex_iterator(); ++i) { - const auto& m = *i; - auto key = s.substr(static_cast(m.position(1)), - static_cast(m.length(1))); - auto val = m.length(2) > 0 - ? s.substr(static_cast(m.position(2)), - static_cast(m.length(2))) - : s.substr(static_cast(m.position(3)), - static_cast(m.length(3))); - auth[key] = val; - } - return true; - } - } - } - return false; - } - - class ContentProviderAdapter { - public: - explicit ContentProviderAdapter(ContentProviderWithoutLength&& content_provider) - : content_provider_(content_provider) {} - - bool operator()(size_t offset, size_t, DataSink& sink) { - return content_provider_(offset, sink); - } - - private: - ContentProviderWithoutLength content_provider_; - }; - - } // namespace detail - - inline std::string hosted_at(const std::string& hostname) { - std::vector addrs; - hosted_at(hostname, addrs); - if (addrs.empty()) { - return std::string(); - } - return addrs[0]; - } - - inline void hosted_at(const std::string& hostname, std::vector& addrs) { - struct addrinfo hints; - struct addrinfo* result; - - memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = 0; - - if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints, &result, 0)) { -#if defined __linux__ && !defined __ANDROID__ - res_init(); -#endif - return; - } - auto se = detail::scope_exit([&] { freeaddrinfo(result); }); - - for (auto rp = result; rp; rp = rp->ai_next) { - const auto& addr = *reinterpret_cast(rp->ai_addr); - std::string ip; - auto dummy = -1; - if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip, dummy)) { - addrs.push_back(ip); - } - } - } - - inline std::string encode_uri_component(const std::string& value) { - std::ostringstream escaped; - escaped.fill('0'); - escaped << std::hex; - - for (auto c : value) { - if (std::isalnum(static_cast(c)) || c == '-' || c == '_' || c == '.' || - c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') { - escaped << c; - } else { - escaped << std::uppercase; - escaped << '%' << std::setw(2) << static_cast(static_cast(c)); - escaped << std::nouppercase; - } - } - - return escaped.str(); - } - - inline std::string encode_uri(const std::string& value) { - std::ostringstream escaped; - escaped.fill('0'); - escaped << std::hex; - - for (auto c : value) { - if (std::isalnum(static_cast(c)) || c == '-' || c == '_' || c == '.' || - c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')' || c == ';' || - c == '/' || c == '?' || c == ':' || c == '@' || c == '&' || c == '=' || c == '+' || - c == '$' || c == ',' || c == '#') { - escaped << c; - } else { - escaped << std::uppercase; - escaped << '%' << std::setw(2) << static_cast(static_cast(c)); - escaped << std::nouppercase; - } - } - - return escaped.str(); - } - - inline std::string decode_uri_component(const std::string& value) { - std::string result; - - for (size_t i = 0; i < value.size(); i++) { - if (value[i] == '%' && i + 2 < value.size()) { - auto val = 0; - if (detail::from_hex_to_i(value, i + 1, 2, val)) { - result += static_cast(val); - i += 2; - } else { - result += value[i]; - } - } else { - result += value[i]; - } - } - - return result; - } - - inline std::string decode_uri(const std::string& value) { - std::string result; - - for (size_t i = 0; i < value.size(); i++) { - if (value[i] == '%' && i + 2 < value.size()) { - auto val = 0; - if (detail::from_hex_to_i(value, i + 1, 2, val)) { - result += static_cast(val); - i += 2; - } else { - result += value[i]; - } - } else { - result += value[i]; - } - } - - return result; - } - - inline std::string encode_path_component(const std::string& component) { - std::string result; - result.reserve(component.size() * 3); - - for (size_t i = 0; i < component.size(); i++) { - auto c = static_cast(component[i]); - - // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~" - if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') { - result += static_cast(c); - } - // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / - // "," / ";" / "=" - else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' || c == ')' || - c == '*' || c == '+' || c == ',' || c == ';' || c == '=') { - result += static_cast(c); - } - // Colon is allowed in path segments except first segment - else if (c == ':') { - result += static_cast(c); - } - // @ is allowed in path - else if (c == '@') { - result += static_cast(c); - } else { - result += '%'; - char hex[3]; - snprintf(hex, sizeof(hex), "%02X", c); - result.append(hex, 2); - } - } - return result; - } - - inline std::string decode_path_component(const std::string& component) { - std::string result; - result.reserve(component.size()); - - for (size_t i = 0; i < component.size(); i++) { - if (component[i] == '%' && i + 1 < component.size()) { - if (component[i + 1] == 'u') { - // Unicode %uXXXX encoding - auto val = 0; - if (detail::from_hex_to_i(component, i + 2, 4, val)) { - // 4 digits Unicode codes - char buff[4]; - size_t len = detail::to_utf8(val, buff); - if (len > 0) { - result.append(buff, len); - } - i += 5; // 'u0000' - } else { - result += component[i]; - } - } else { - // Standard %XX encoding - auto val = 0; - if (detail::from_hex_to_i(component, i + 1, 2, val)) { - // 2 digits hex codes - result += static_cast(val); - i += 2; // 'XX' - } else { - result += component[i]; - } - } - } else { - result += component[i]; - } - } - return result; - } - - inline std::string encode_query_component(const std::string& component, bool space_as_plus) { - std::string result; - result.reserve(component.size() * 3); - - for (size_t i = 0; i < component.size(); i++) { - auto c = static_cast(component[i]); - - // Unreserved characters per RFC 3986 - if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') { - result += static_cast(c); - } - // Space handling - else if (c == ' ') { - if (space_as_plus) { - result += '+'; - } else { - result += "%20"; - } - } - // Plus sign handling - else if (c == '+') { - if (space_as_plus) { - result += "%2B"; - } else { - result += static_cast(c); - } - } - // Query-safe sub-delimiters (excluding & and = which are query delimiters) - else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' || c == '*' || - c == ',' || c == ';') { - result += static_cast(c); - } - // Colon and @ are allowed in query - else if (c == ':' || c == '@') { - result += static_cast(c); - } - // Forward slash is allowed in query values - else if (c == '/') { - result += static_cast(c); - } - // Question mark is allowed in query values (after first ?) - else if (c == '?') { - result += static_cast(c); - } else { - result += '%'; - char hex[3]; - snprintf(hex, sizeof(hex), "%02X", c); - result.append(hex, 2); - } - } - return result; - } - - inline std::string decode_query_component(const std::string& component, bool plus_as_space) { - std::string result; - result.reserve(component.size()); - - for (size_t i = 0; i < component.size(); i++) { - if (component[i] == '%' && i + 2 < component.size()) { - std::string hex = component.substr(i + 1, 2); - char* end; - unsigned long value = std::strtoul(hex.c_str(), &end, 16); - if (end == hex.c_str() + 2) { - result += static_cast(value); - i += 2; - } else { - result += component[i]; - } - } else if (component[i] == '+' && plus_as_space) { - result += ' '; // + becomes space in form-urlencoded - } else { - result += component[i]; - } - } - return result; - } - - inline std::string append_query_params(const std::string& path, const Params& params) { - std::string path_with_query = path; - thread_local const std::regex re("[^?]+\\?.*"); - auto delm = std::regex_match(path, re) ? '&' : '?'; - path_with_query += delm + detail::params_to_query_str(params); - return path_with_query; - } - - // Header utilities - inline std::pair make_range_header(const Ranges& ranges) { - std::string field = "bytes="; - auto i = 0; - for (const auto& r : ranges) { - if (i != 0) { - field += ", "; - } - if (r.first != -1) { - field += std::to_string(r.first); - } - field += '-'; - if (r.second != -1) { - field += std::to_string(r.second); - } - i++; - } - return std::make_pair("Range", std::move(field)); - } - - inline std::pair make_basic_authentication_header( - const std::string& username, const std::string& password, bool is_proxy) { - auto field = "Basic " + detail::base64_encode(username + ":" + password); - auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; - return std::make_pair(key, std::move(field)); - } - - inline std::pair make_bearer_token_authentication_header( - const std::string& token, bool is_proxy = false) { - auto field = "Bearer " + token; - auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; - return std::make_pair(key, std::move(field)); - } - - // Request implementation - inline bool Request::has_header(const std::string& key) const { - return detail::has_header(headers, key); - } - - inline std::string Request::get_header_value(const std::string& key, const char* def, - size_t id) const { - return detail::get_header_value(headers, key, def, id); - } - - inline size_t Request::get_header_value_count(const std::string& key) const { - auto r = headers.equal_range(key); - return static_cast(std::distance(r.first, r.second)); - } - - inline void Request::set_header(const std::string& key, const std::string& val) { - if (detail::fields::is_field_name(key) && detail::fields::is_field_value(val)) { - headers.emplace(key, val); - } - } - - inline bool Request::has_trailer(const std::string& key) const { - return trailers.find(key) != trailers.end(); - } - - inline std::string Request::get_trailer_value(const std::string& key, size_t id) const { - auto rng = trailers.equal_range(key); - auto it = rng.first; - std::advance(it, static_cast(id)); - if (it != rng.second) { - return it->second; - } - return std::string(); - } - - inline size_t Request::get_trailer_value_count(const std::string& key) const { - auto r = trailers.equal_range(key); - return static_cast(std::distance(r.first, r.second)); - } - - inline bool Request::has_param(const std::string& key) const { - return params.find(key) != params.end(); - } - - inline std::string Request::get_param_value(const std::string& key, size_t id) const { - auto rng = params.equal_range(key); - auto it = rng.first; - std::advance(it, static_cast(id)); - if (it != rng.second) { - return it->second; - } - return std::string(); - } - - inline size_t Request::get_param_value_count(const std::string& key) const { - auto r = params.equal_range(key); - return static_cast(std::distance(r.first, r.second)); - } - - inline bool Request::is_multipart_form_data() const { - const auto& content_type = get_header_value("Content-Type"); - return !content_type.rfind("multipart/form-data", 0); - } - - // Multipart FormData implementation - inline std::string MultipartFormData::get_field(const std::string& key, size_t id) const { - auto rng = fields.equal_range(key); - auto it = rng.first; - std::advance(it, static_cast(id)); - if (it != rng.second) { - return it->second.content; - } - return std::string(); - } - - inline std::vector MultipartFormData::get_fields(const std::string& key) const { - std::vector values; - auto rng = fields.equal_range(key); - for (auto it = rng.first; it != rng.second; it++) { - values.push_back(it->second.content); - } - return values; - } - - inline bool MultipartFormData::has_field(const std::string& key) const { - return fields.find(key) != fields.end(); - } - - inline size_t MultipartFormData::get_field_count(const std::string& key) const { - auto r = fields.equal_range(key); - return static_cast(std::distance(r.first, r.second)); - } - - inline FormData MultipartFormData::get_file(const std::string& key, size_t id) const { - auto rng = files.equal_range(key); - auto it = rng.first; - std::advance(it, static_cast(id)); - if (it != rng.second) { - return it->second; - } - return FormData(); - } - - inline std::vector MultipartFormData::get_files(const std::string& key) const { - std::vector values; - auto rng = files.equal_range(key); - for (auto it = rng.first; it != rng.second; it++) { - values.push_back(it->second); - } - return values; - } - - inline bool MultipartFormData::has_file(const std::string& key) const { - return files.find(key) != files.end(); - } - - inline size_t MultipartFormData::get_file_count(const std::string& key) const { - auto r = files.equal_range(key); - return static_cast(std::distance(r.first, r.second)); - } - - // Response implementation - inline bool Response::has_header(const std::string& key) const { - return headers.find(key) != headers.end(); - } - - inline std::string Response::get_header_value(const std::string& key, const char* def, - size_t id) const { - return detail::get_header_value(headers, key, def, id); - } - - inline size_t Response::get_header_value_count(const std::string& key) const { - auto r = headers.equal_range(key); - return static_cast(std::distance(r.first, r.second)); - } - - inline void Response::set_header(const std::string& key, const std::string& val) { - if (detail::fields::is_field_name(key) && detail::fields::is_field_value(val)) { - headers.emplace(key, val); - } - } - inline bool Response::has_trailer(const std::string& key) const { - return trailers.find(key) != trailers.end(); - } - - inline std::string Response::get_trailer_value(const std::string& key, size_t id) const { - auto rng = trailers.equal_range(key); - auto it = rng.first; - std::advance(it, static_cast(id)); - if (it != rng.second) { - return it->second; - } - return std::string(); - } - - inline size_t Response::get_trailer_value_count(const std::string& key) const { - auto r = trailers.equal_range(key); - return static_cast(std::distance(r.first, r.second)); - } - - inline void Response::set_redirect(const std::string& url, int stat) { - if (detail::fields::is_field_value(url)) { - set_header("Location", url); - if (300 <= stat && stat < 400) { - this->status = stat; - } else { - this->status = StatusCode::Found_302; - } - } - } - - inline void Response::set_content(const char* s, size_t n, const std::string& content_type) { - body.assign(s, n); - - auto rng = headers.equal_range("Content-Type"); - headers.erase(rng.first, rng.second); - set_header("Content-Type", content_type); - } - - inline void Response::set_content(const std::string& s, const std::string& content_type) { - set_content(s.data(), s.size(), content_type); - } - - inline void Response::set_content(std::string&& s, const std::string& content_type) { - body = std::move(s); - - auto rng = headers.equal_range("Content-Type"); - headers.erase(rng.first, rng.second); - set_header("Content-Type", content_type); - } - - inline void Response::set_content_provider(size_t in_length, const std::string& content_type, - ContentProvider provider, - ContentProviderResourceReleaser resource_releaser) { - set_header("Content-Type", content_type); - content_length_ = in_length; - if (in_length > 0) { - content_provider_ = std::move(provider); - } - content_provider_resource_releaser_ = std::move(resource_releaser); - is_chunked_content_provider_ = false; - } - - inline void Response::set_content_provider(const std::string& content_type, - ContentProviderWithoutLength provider, - ContentProviderResourceReleaser resource_releaser) { - set_header("Content-Type", content_type); - content_length_ = 0; - content_provider_ = detail::ContentProviderAdapter(std::move(provider)); - content_provider_resource_releaser_ = std::move(resource_releaser); - is_chunked_content_provider_ = false; - } - - inline void Response::set_chunked_content_provider( - const std::string& content_type, ContentProviderWithoutLength provider, - ContentProviderResourceReleaser resource_releaser) { - set_header("Content-Type", content_type); - content_length_ = 0; - content_provider_ = detail::ContentProviderAdapter(std::move(provider)); - content_provider_resource_releaser_ = std::move(resource_releaser); - is_chunked_content_provider_ = true; - } - - inline void Response::set_file_content(const std::string& path, - const std::string& content_type) { - file_content_path_ = path; - file_content_content_type_ = content_type; - } - - inline void Response::set_file_content(const std::string& path) { file_content_path_ = path; } - - // Result implementation - inline bool Result::has_request_header(const std::string& key) const { - return request_headers_.find(key) != request_headers_.end(); - } - - inline std::string Result::get_request_header_value(const std::string& key, const char* def, - size_t id) const { - return detail::get_header_value(request_headers_, key, def, id); - } - - inline size_t Result::get_request_header_value_count(const std::string& key) const { - auto r = request_headers_.equal_range(key); - return static_cast(std::distance(r.first, r.second)); - } - - // Stream implementation - inline ssize_t Stream::write(const char* ptr) { return write(ptr, strlen(ptr)); } - - inline ssize_t Stream::write(const std::string& s) { return write(s.data(), s.size()); } - - namespace detail { - - inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec, - time_t timeout_sec, time_t timeout_usec, - time_t& actual_timeout_sec, time_t& actual_timeout_usec) { - auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000); - - auto actual_timeout_msec = (std::min)(max_timeout_msec - duration_msec, timeout_msec); - - if (actual_timeout_msec < 0) { - actual_timeout_msec = 0; - } - - actual_timeout_sec = actual_timeout_msec / 1000; - actual_timeout_usec = (actual_timeout_msec % 1000) * 1000; - } - - // Socket stream implementation - inline SocketStream::SocketStream( - socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec, - time_t write_timeout_sec, time_t write_timeout_usec, time_t max_timeout_msec, - std::chrono::time_point start_time) - : sock_(sock), - read_timeout_sec_(read_timeout_sec), - read_timeout_usec_(read_timeout_usec), - write_timeout_sec_(write_timeout_sec), - write_timeout_usec_(write_timeout_usec), - max_timeout_msec_(max_timeout_msec), - start_time_(start_time), - read_buff_(read_buff_size_, 0) {} - - inline SocketStream::~SocketStream() = default; - - inline bool SocketStream::is_readable() const { - return read_buff_off_ < read_buff_content_size_; - } - - inline bool SocketStream::wait_readable() const { - if (max_timeout_msec_ <= 0) { - return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0; - } - - time_t read_timeout_sec; - time_t read_timeout_usec; - calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_, - read_timeout_usec_, read_timeout_sec, read_timeout_usec); - - return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0; - } - - inline bool SocketStream::wait_writable() const { - return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 && - is_socket_alive(sock_); - } - - inline ssize_t SocketStream::read(char* ptr, size_t size) { -#ifdef _WIN32 - size = (std::min)(size, static_cast((std::numeric_limits::max)())); -#else - size = (std::min)(size, static_cast((std::numeric_limits::max)())); -#endif - - if (read_buff_off_ < read_buff_content_size_) { - auto remaining_size = read_buff_content_size_ - read_buff_off_; - if (size <= remaining_size) { - memcpy(ptr, read_buff_.data() + read_buff_off_, size); - read_buff_off_ += size; - return static_cast(size); - } else { - memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size); - read_buff_off_ += remaining_size; - return static_cast(remaining_size); - } - } - - if (!wait_readable()) { - return -1; - } - - read_buff_off_ = 0; - read_buff_content_size_ = 0; - - if (size < read_buff_size_) { - auto n = - read_socket(sock_, read_buff_.data(), read_buff_size_, CPPHTTPLIB_RECV_FLAGS); - if (n <= 0) { - return n; - } else if (n <= static_cast(size)) { - memcpy(ptr, read_buff_.data(), static_cast(n)); - return n; - } else { - memcpy(ptr, read_buff_.data(), size); - read_buff_off_ = size; - read_buff_content_size_ = static_cast(n); - return static_cast(size); - } - } else { - return read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS); - } - } - - inline ssize_t SocketStream::write(const char* ptr, size_t size) { - if (!wait_writable()) { - return -1; - } - -#if defined(_WIN32) && !defined(_WIN64) - size = (std::min)(size, static_cast((std::numeric_limits::max)())); -#endif - - return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS); - } - - inline void SocketStream::get_remote_ip_and_port(std::string& ip, int& port) const { - return detail::get_remote_ip_and_port(sock_, ip, port); - } - - inline void SocketStream::get_local_ip_and_port(std::string& ip, int& port) const { - return detail::get_local_ip_and_port(sock_, ip, port); - } - - inline socket_t SocketStream::socket() const { return sock_; } - - inline time_t SocketStream::duration() const { - return std::chrono::duration_cast( - std::chrono::steady_clock::now() - start_time_) - .count(); - } - - // Buffer stream implementation - inline bool BufferStream::is_readable() const { return true; } - - inline bool BufferStream::wait_readable() const { return true; } - - inline bool BufferStream::wait_writable() const { return true; } - - inline ssize_t BufferStream::read(char* ptr, size_t size) { -#if defined(_MSC_VER) && _MSC_VER < 1910 - auto len_read = buffer._Copy_s(ptr, size, size, position); -#else - auto len_read = buffer.copy(ptr, size, position); -#endif - position += static_cast(len_read); - return static_cast(len_read); - } - - inline ssize_t BufferStream::write(const char* ptr, size_t size) { - buffer.append(ptr, size); - return static_cast(size); - } - - inline void BufferStream::get_remote_ip_and_port(std::string& /*ip*/, int& /*port*/) const { - } - - inline void BufferStream::get_local_ip_and_port(std::string& /*ip*/, int& /*port*/) const {} - - inline socket_t BufferStream::socket() const { return 0; } - - inline time_t BufferStream::duration() const { return 0; } - - inline const std::string& BufferStream::get_buffer() const { return buffer; } - - inline PathParamsMatcher::PathParamsMatcher(const std::string& pattern) - : MatcherBase(pattern) { - constexpr const char marker[] = "/:"; - - // One past the last ending position of a path param substring - std::size_t last_param_end = 0; - -#ifndef CPPHTTPLIB_NO_EXCEPTIONS - // Needed to ensure that parameter names are unique during matcher - // construction - // If exceptions are disabled, only last duplicate path - // parameter will be set - std::unordered_set param_name_set; -#endif - - while (true) { - const auto marker_pos = - pattern.find(marker, last_param_end == 0 ? last_param_end : last_param_end - 1); - if (marker_pos == std::string::npos) { - break; - } - - static_fragments_.push_back( - pattern.substr(last_param_end, marker_pos - last_param_end + 1)); - - const auto param_name_start = marker_pos + str_len(marker); - - auto sep_pos = pattern.find(separator, param_name_start); - if (sep_pos == std::string::npos) { - sep_pos = pattern.length(); - } - - auto param_name = pattern.substr(param_name_start, sep_pos - param_name_start); - -#ifndef CPPHTTPLIB_NO_EXCEPTIONS - if (param_name_set.find(param_name) != param_name_set.cend()) { - std::string msg = "Encountered path parameter '" + param_name + - "' multiple times in route pattern '" + pattern + "'."; - throw std::invalid_argument(msg); - } -#endif - - param_names_.push_back(std::move(param_name)); - - last_param_end = sep_pos + 1; - } - - if (last_param_end < pattern.length()) { - static_fragments_.push_back(pattern.substr(last_param_end)); - } - } - - inline bool PathParamsMatcher::match(Request& request) const { - request.matches = std::smatch(); - request.path_params.clear(); - request.path_params.reserve(param_names_.size()); - - // One past the position at which the path matched the pattern last time - std::size_t starting_pos = 0; - for (size_t i = 0; i < static_fragments_.size(); ++i) { - const auto& fragment = static_fragments_[i]; - - if (starting_pos + fragment.length() > request.path.length()) { - return false; - } - - // Avoid unnecessary allocation by using strncmp instead of substr + - // comparison - if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(), - fragment.length()) != 0) { - return false; - } - - starting_pos += fragment.length(); - - // Should only happen when we have a static fragment after a param - // Example: '/users/:id/subscriptions' - // The 'subscriptions' fragment here does not have a corresponding param - if (i >= param_names_.size()) { - continue; - } - - auto sep_pos = request.path.find(separator, starting_pos); - if (sep_pos == std::string::npos) { - sep_pos = request.path.length(); - } - - const auto& param_name = param_names_[i]; - - request.path_params.emplace( - param_name, request.path.substr(starting_pos, sep_pos - starting_pos)); - - // Mark everything up to '/' as matched - starting_pos = sep_pos + 1; - } - // Returns false if the path is longer than the pattern - return starting_pos >= request.path.length(); - } - - inline bool RegexMatcher::match(Request& request) const { - request.path_params.clear(); - return std::regex_match(request.path, request.matches, regex_); - } - - inline std::string make_host_and_port_string(const std::string& host, int port, - bool is_ssl) { - std::string result; - - // Enclose IPv6 address in brackets (but not if already enclosed) - if (host.find(':') == std::string::npos || (!host.empty() && host[0] == '[')) { - // IPv4, hostname, or already bracketed IPv6 - result = host; - } else { - // IPv6 address without brackets - result = "[" + host + "]"; - } - - // Append port if not default - if ((!is_ssl && port == 80) || (is_ssl && port == 443)) { - ; // do nothing - } else { - result += ":" + std::to_string(port); - } - - return result; - } - - } // namespace detail - - // HTTP server implementation - inline Server::Server() - : new_task_queue([] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) { -#ifndef _WIN32 - signal(SIGPIPE, SIG_IGN); -#endif - } - - inline Server::~Server() = default; - - inline std::unique_ptr Server::make_matcher(const std::string& pattern) { - if (pattern.find("/:") != std::string::npos) { - return detail::make_unique(pattern); - } else { - return detail::make_unique(pattern); - } - } - - inline Server& Server::Get(const std::string& pattern, Handler handler) { - get_handlers_.emplace_back(make_matcher(pattern), std::move(handler)); - return *this; - } - - inline Server& Server::Post(const std::string& pattern, Handler handler) { - post_handlers_.emplace_back(make_matcher(pattern), std::move(handler)); - return *this; - } - - inline Server& Server::Post(const std::string& pattern, HandlerWithContentReader handler) { - post_handlers_for_content_reader_.emplace_back(make_matcher(pattern), std::move(handler)); - return *this; - } - - inline Server& Server::Put(const std::string& pattern, Handler handler) { - put_handlers_.emplace_back(make_matcher(pattern), std::move(handler)); - return *this; - } - - inline Server& Server::Put(const std::string& pattern, HandlerWithContentReader handler) { - put_handlers_for_content_reader_.emplace_back(make_matcher(pattern), std::move(handler)); - return *this; - } - - inline Server& Server::Patch(const std::string& pattern, Handler handler) { - patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler)); - return *this; - } - - inline Server& Server::Patch(const std::string& pattern, HandlerWithContentReader handler) { - patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern), std::move(handler)); - return *this; - } - - inline Server& Server::Delete(const std::string& pattern, Handler handler) { - delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler)); - return *this; - } - - inline Server& Server::Delete(const std::string& pattern, HandlerWithContentReader handler) { - delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern), std::move(handler)); - return *this; - } - - inline Server& Server::Options(const std::string& pattern, Handler handler) { - options_handlers_.emplace_back(make_matcher(pattern), std::move(handler)); - return *this; - } - - inline bool Server::set_base_dir(const std::string& dir, const std::string& mount_point) { - return set_mount_point(mount_point, dir); - } - - inline bool Server::set_mount_point(const std::string& mount_point, const std::string& dir, - Headers headers) { - detail::FileStat stat(dir); - if (stat.is_dir()) { - std::string mnt = !mount_point.empty() ? mount_point : "/"; - if (!mnt.empty() && mnt[0] == '/') { - base_dirs_.push_back({mnt, dir, std::move(headers)}); - return true; - } - } - return false; - } - - inline bool Server::remove_mount_point(const std::string& mount_point) { - for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) { - if (it->mount_point == mount_point) { - base_dirs_.erase(it); - return true; - } - } - return false; - } - - inline Server& Server::set_file_extension_and_mimetype_mapping(const std::string& ext, - const std::string& mime) { - file_extension_and_mimetype_map_[ext] = mime; - return *this; - } - - inline Server& Server::set_default_file_mimetype(const std::string& mime) { - default_file_mimetype_ = mime; - return *this; - } - - inline Server& Server::set_file_request_handler(Handler handler) { - file_request_handler_ = std::move(handler); - return *this; - } - - inline Server& Server::set_error_handler_core(HandlerWithResponse handler, std::true_type) { - error_handler_ = std::move(handler); - return *this; - } - - inline Server& Server::set_error_handler_core(Handler handler, std::false_type) { - error_handler_ = [handler](const Request& req, Response& res) { - handler(req, res); - return HandlerResponse::Handled; - }; - return *this; - } - - inline Server& Server::set_exception_handler(ExceptionHandler handler) { - exception_handler_ = std::move(handler); - return *this; - } - - inline Server& Server::set_pre_routing_handler(HandlerWithResponse handler) { - pre_routing_handler_ = std::move(handler); - return *this; - } - - inline Server& Server::set_post_routing_handler(Handler handler) { - post_routing_handler_ = std::move(handler); - return *this; - } - - inline Server& Server::set_pre_request_handler(HandlerWithResponse handler) { - pre_request_handler_ = std::move(handler); - return *this; - } - - inline Server& Server::set_logger(Logger logger) { - logger_ = std::move(logger); - return *this; - } - - inline Server& Server::set_error_logger(ErrorLogger error_logger) { - error_logger_ = std::move(error_logger); - return *this; - } - - inline Server& Server::set_pre_compression_logger(Logger logger) { - pre_compression_logger_ = std::move(logger); - return *this; - } - - inline Server& Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) { - expect_100_continue_handler_ = std::move(handler); - return *this; - } - - inline Server& Server::set_address_family(int family) { - address_family_ = family; - return *this; - } - - inline Server& Server::set_tcp_nodelay(bool on) { - tcp_nodelay_ = on; - return *this; - } - - inline Server& Server::set_ipv6_v6only(bool on) { - ipv6_v6only_ = on; - return *this; - } - - inline Server& Server::set_socket_options(SocketOptions socket_options) { - socket_options_ = std::move(socket_options); - return *this; - } - - inline Server& Server::set_default_headers(Headers headers) { - default_headers_ = std::move(headers); - return *this; - } - - inline Server& Server::set_header_writer( - std::function const& writer) { - header_writer_ = writer; - return *this; - } - - inline Server& Server::set_trusted_proxies(const std::vector& proxies) { - trusted_proxies_ = proxies; - return *this; - } - - inline Server& Server::set_keep_alive_max_count(size_t count) { - keep_alive_max_count_ = count; - return *this; - } - - inline Server& Server::set_keep_alive_timeout(time_t sec) { - keep_alive_timeout_sec_ = sec; - return *this; - } - - inline Server& Server::set_read_timeout(time_t sec, time_t usec) { - read_timeout_sec_ = sec; - read_timeout_usec_ = usec; - return *this; - } - - inline Server& Server::set_write_timeout(time_t sec, time_t usec) { - write_timeout_sec_ = sec; - write_timeout_usec_ = usec; - return *this; - } - - inline Server& Server::set_idle_interval(time_t sec, time_t usec) { - idle_interval_sec_ = sec; - idle_interval_usec_ = usec; - return *this; - } - - inline Server& Server::set_payload_max_length(size_t length) { - payload_max_length_ = length; - return *this; - } - - inline bool Server::bind_to_port(const std::string& host, int port, int socket_flags) { - auto ret = bind_internal(host, port, socket_flags); - if (ret == -1) { - is_decommissioned = true; - } - return ret >= 0; - } - inline int Server::bind_to_any_port(const std::string& host, int socket_flags) { - auto ret = bind_internal(host, 0, socket_flags); - if (ret == -1) { - is_decommissioned = true; - } - return ret; - } - - inline bool Server::listen_after_bind() { return listen_internal(); } - - inline bool Server::listen(const std::string& host, int port, int socket_flags) { - return bind_to_port(host, port, socket_flags) && listen_internal(); - } - - inline bool Server::is_running() const { return is_running_; } - - inline void Server::wait_until_ready() const { - while (!is_running_ && !is_decommissioned) { - std::this_thread::sleep_for(std::chrono::milliseconds{1}); - } - } - - inline void Server::stop() { - if (is_running_) { - assert(svr_sock_ != INVALID_SOCKET); - std::atomic sock(svr_sock_.exchange(INVALID_SOCKET)); - detail::shutdown_socket(sock); - detail::close_socket(sock); - } - is_decommissioned = false; - } - - inline void Server::decommission() { is_decommissioned = true; } - - inline bool Server::parse_request_line(const char* s, Request& req) const { - auto len = strlen(s); - if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { - return false; - } - len -= 2; - - { - size_t count = 0; - - detail::split(s, s + len, ' ', [&](const char* b, const char* e) { - switch (count) { - case 0: - req.method = std::string(b, e); - break; - case 1: - req.target = std::string(b, e); - break; - case 2: - req.version = std::string(b, e); - break; - default: - break; - } - count++; - }); - - if (count != 3) { - return false; - } - } - - thread_local const std::set methods{ - "GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"}; - - if (methods.find(req.method) == methods.end()) { - output_error_log(Error::InvalidHTTPMethod, &req); - return false; - } - - if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") { - output_error_log(Error::InvalidHTTPVersion, &req); - return false; - } - - { - // Skip URL fragment - for (size_t i = 0; i < req.target.size(); i++) { - if (req.target[i] == '#') { - req.target.erase(i); - break; - } - } - - detail::divide(req.target, '?', - [&](const char* lhs_data, std::size_t lhs_size, const char* rhs_data, - std::size_t rhs_size) { - req.path = decode_path_component(std::string(lhs_data, lhs_size)); - detail::parse_query_text(rhs_data, rhs_size, req.params); - }); - } - - return true; - } - - inline bool Server::write_response(Stream& strm, bool close_connection, Request& req, - Response& res) { - // NOTE: `req.ranges` should be empty, otherwise it will be applied - // incorrectly to the error content. - req.ranges.clear(); - return write_response_core(strm, close_connection, req, res, false); - } - - inline bool Server::write_response_with_content(Stream& strm, bool close_connection, - const Request& req, Response& res) { - return write_response_core(strm, close_connection, req, res, true); - } - - inline bool Server::write_response_core(Stream& strm, bool close_connection, const Request& req, - Response& res, bool need_apply_ranges) { - assert(res.status != -1); - - if (400 <= res.status && error_handler_ && - error_handler_(req, res) == HandlerResponse::Handled) { - need_apply_ranges = true; - } - - std::string content_type; - std::string boundary; - if (need_apply_ranges) { - apply_ranges(req, res, content_type, boundary); - } - - // Prepare additional headers - if (close_connection || req.get_header_value("Connection") == "close" || - 400 <= res.status) { // Don't leave connections open after errors - res.set_header("Connection", "close"); - } else { - std::string s = "timeout="; - s += std::to_string(keep_alive_timeout_sec_); - s += ", max="; - s += std::to_string(keep_alive_max_count_); - res.set_header("Keep-Alive", s); - } - - if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) && - !res.has_header("Content-Type")) { - res.set_header("Content-Type", "text/plain"); - } - - if (res.body.empty() && !res.content_length_ && !res.content_provider_ && - !res.has_header("Content-Length")) { - res.set_header("Content-Length", "0"); - } - - if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) { - res.set_header("Accept-Ranges", "bytes"); - } - - if (post_routing_handler_) { - post_routing_handler_(req, res); - } - - // Response line and headers - { - detail::BufferStream bstrm; - if (!detail::write_response_line(bstrm, res.status)) { - return false; - } - if (!header_writer_(bstrm, res.headers)) { - return false; - } - - // Flush buffer - auto& data = bstrm.get_buffer(); - detail::write_data(strm, data.data(), data.size()); - } - - // Body - auto ret = true; - if (req.method != "HEAD") { - if (!res.body.empty()) { - if (!detail::write_data(strm, res.body.data(), res.body.size())) { - ret = false; - } - } else if (res.content_provider_) { - if (write_content_with_provider(strm, req, res, boundary, content_type)) { - res.content_provider_success_ = true; - } else { - ret = false; - } - } - } - - // Log - output_log(req, res); - - return ret; - } - - inline bool Server::write_content_with_provider(Stream& strm, const Request& req, Response& res, - const std::string& boundary, - const std::string& content_type) { - auto is_shutting_down = [this]() { return this->svr_sock_ == INVALID_SOCKET; }; - - if (res.content_length_ > 0) { - if (req.ranges.empty()) { - return detail::write_content(strm, res.content_provider_, 0, res.content_length_, - is_shutting_down); - } else if (req.ranges.size() == 1) { - auto offset_and_length = - detail::get_range_offset_and_length(req.ranges[0], res.content_length_); - - return detail::write_content(strm, res.content_provider_, offset_and_length.first, - offset_and_length.second, is_shutting_down); - } else { - return detail::write_multipart_ranges_data(strm, req, res, boundary, content_type, - res.content_length_, is_shutting_down); - } - } else { - if (res.is_chunked_content_provider_) { - auto type = detail::encoding_type(req, res); - - std::unique_ptr compressor; - if (type == detail::EncodingType::Gzip) { -#ifdef CPPHTTPLIB_ZLIB_SUPPORT - compressor = detail::make_unique(); -#endif - } else if (type == detail::EncodingType::Brotli) { -#ifdef CPPHTTPLIB_BROTLI_SUPPORT - compressor = detail::make_unique(); -#endif - } else if (type == detail::EncodingType::Zstd) { -#ifdef CPPHTTPLIB_ZSTD_SUPPORT - compressor = detail::make_unique(); -#endif - } else { - compressor = detail::make_unique(); - } - assert(compressor != nullptr); - - return detail::write_content_chunked(strm, res.content_provider_, is_shutting_down, - *compressor); - } else { - return detail::write_content_without_length(strm, res.content_provider_, - is_shutting_down); - } - } - } - - inline bool Server::read_content(Stream& strm, Request& req, Response& res) { - FormFields::iterator cur_field; - FormFiles::iterator cur_file; - auto is_text_field = false; - size_t count = 0; - if (read_content_core( - strm, req, res, - // Regular - [&](const char* buf, size_t n) { - if (req.body.size() + n > req.body.max_size()) { - return false; - } - req.body.append(buf, n); - return true; - }, - // Multipart FormData - [&](const FormData& file) { - if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) { - output_error_log(Error::TooManyFormDataFiles, &req); - return false; - } - - if (file.filename.empty()) { - cur_field = req.form.fields.emplace( - file.name, FormField{file.name, file.content, file.headers}); - is_text_field = true; - } else { - cur_file = req.form.files.emplace(file.name, file); - is_text_field = false; - } - return true; - }, - [&](const char* buf, size_t n) { - if (is_text_field) { - auto& content = cur_field->second.content; - if (content.size() + n > content.max_size()) { - return false; - } - content.append(buf, n); - } else { - auto& content = cur_file->second.content; - if (content.size() + n > content.max_size()) { - return false; - } - content.append(buf, n); - } - return true; - })) { - const auto& content_type = req.get_header_value("Content-Type"); - if (!content_type.find("application/x-www-form-urlencoded")) { - if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) { - res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414? - output_error_log(Error::ExceedMaxPayloadSize, &req); - return false; - } - detail::parse_query_text(req.body, req.params); - } - return true; - } - return false; - } - - inline bool Server::read_content_with_content_receiver(Stream& strm, Request& req, - Response& res, ContentReceiver receiver, - FormDataHeader multipart_header, - ContentReceiver multipart_receiver) { - return read_content_core(strm, req, res, std::move(receiver), std::move(multipart_header), - std::move(multipart_receiver)); - } - - inline bool Server::read_content_core(Stream& strm, Request& req, Response& res, - ContentReceiver receiver, FormDataHeader multipart_header, - ContentReceiver multipart_receiver) const { - detail::FormDataParser multipart_form_data_parser; - ContentReceiverWithProgress out; - - if (req.is_multipart_form_data()) { - const auto& content_type = req.get_header_value("Content-Type"); - std::string boundary; - if (!detail::parse_multipart_boundary(content_type, boundary)) { - res.status = StatusCode::BadRequest_400; - output_error_log(Error::MultipartParsing, &req); - return false; - } - - multipart_form_data_parser.set_boundary(std::move(boundary)); - out = [&](const char* buf, size_t n, size_t /*off*/, size_t /*len*/) { - return multipart_form_data_parser.parse(buf, n, multipart_header, - multipart_receiver); - }; - } else { - out = [receiver](const char* buf, size_t n, size_t /*off*/, size_t /*len*/) { - return receiver(buf, n); - }; - } - - // RFC 7230 Section 3.3.3: If this is a request message and none of the above - // are true (no Transfer-Encoding and no Content-Length), then the message - // body length is zero (no message body is present). - if (!req.has_header("Content-Length") && - !detail::is_chunked_transfer_encoding(req.headers)) { - return true; - } - - if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr, out, true)) { - return false; - } - - if (req.is_multipart_form_data()) { - if (!multipart_form_data_parser.is_valid()) { - res.status = StatusCode::BadRequest_400; - output_error_log(Error::MultipartParsing, &req); - return false; - } - } - - return true; - } - - inline bool Server::handle_file_request(const Request& req, Response& res) { - for (const auto& entry : base_dirs_) { - // Prefix match - if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) { - std::string sub_path = "/" + req.path.substr(entry.mount_point.size()); - if (detail::is_valid_path(sub_path)) { - auto path = entry.base_dir + sub_path; - if (path.back() == '/') { - path += "index.html"; - } - - detail::FileStat stat(path); - - if (stat.is_dir()) { - res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301); - return true; - } - - if (stat.is_file()) { - for (const auto& kv : entry.headers) { - res.set_header(kv.first, kv.second); - } - - auto mm = std::make_shared(path.c_str()); - if (!mm->is_open()) { - output_error_log(Error::OpenFile, &req); - return false; - } - - res.set_content_provider( - mm->size(), - detail::find_content_type(path, file_extension_and_mimetype_map_, - default_file_mimetype_), - [mm](size_t offset, size_t length, DataSink& sink) -> bool { - sink.write(mm->data() + offset, length); - return true; - }); - - if (req.method != "HEAD" && file_request_handler_) { - file_request_handler_(req, res); - } - - return true; - } else { - output_error_log(Error::OpenFile, &req); - } - } - } - } - return false; - } - - inline socket_t Server::create_server_socket(const std::string& host, int port, - int socket_flags, - SocketOptions socket_options) const { - return detail::create_socket( - host, std::string(), port, address_family_, socket_flags, tcp_nodelay_, ipv6_v6only_, - std::move(socket_options), - [&](socket_t sock, struct addrinfo& ai, bool& /*quit*/) -> bool { - if (::bind(sock, ai.ai_addr, static_cast(ai.ai_addrlen))) { - output_error_log(Error::BindIPAddress, nullptr); - return false; - } - if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) { - output_error_log(Error::Listen, nullptr); - return false; - } - return true; - }); - } - - inline int Server::bind_internal(const std::string& host, int port, int socket_flags) { - if (is_decommissioned) { - return -1; - } - - if (!is_valid()) { - return -1; - } - - svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_); - if (svr_sock_ == INVALID_SOCKET) { - return -1; - } - - if (port == 0) { - struct sockaddr_storage addr; - socklen_t addr_len = sizeof(addr); - if (getsockname(svr_sock_, reinterpret_cast(&addr), &addr_len) == - -1) { - output_error_log(Error::GetSockName, nullptr); - return -1; - } - if (addr.ss_family == AF_INET) { - return ntohs(reinterpret_cast(&addr)->sin_port); - } else if (addr.ss_family == AF_INET6) { - return ntohs(reinterpret_cast(&addr)->sin6_port); - } else { - output_error_log(Error::UnsupportedAddressFamily, nullptr); - return -1; - } - } else { - return port; - } - } - - inline bool Server::listen_internal() { - if (is_decommissioned) { - return false; - } - - auto ret = true; - is_running_ = true; - auto se = detail::scope_exit([&]() { is_running_ = false; }); - - { - std::unique_ptr task_queue(new_task_queue()); - - while (svr_sock_ != INVALID_SOCKET) { -#ifndef _WIN32 - if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) { -#endif - auto val = - detail::select_read(svr_sock_, idle_interval_sec_, idle_interval_usec_); - if (val == 0) { // Timeout - task_queue->on_idle(); - continue; - } -#ifndef _WIN32 - } -#endif - -#if defined _WIN32 - // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT, - // OVERLAPPED - socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0); -#elif defined SOCK_CLOEXEC - socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC); -#else - socket_t sock = accept(svr_sock_, nullptr, nullptr); -#endif - - if (sock == INVALID_SOCKET) { - if (errno == EMFILE) { - // The per-process limit of open file descriptors has been reached. - // Try to accept new connections after a short sleep. - std::this_thread::sleep_for(std::chrono::microseconds{1}); - continue; - } else if (errno == EINTR || errno == EAGAIN) { - continue; - } - if (svr_sock_ != INVALID_SOCKET) { - detail::close_socket(svr_sock_); - ret = false; - output_error_log(Error::Connection, nullptr); - } else { - ; // The server socket was closed by user. - } - break; - } - - detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec_, - read_timeout_usec_); - detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec_, - write_timeout_usec_); - - if (!task_queue->enqueue([this, sock]() { process_and_close_socket(sock); })) { - output_error_log(Error::ResourceExhaustion, nullptr); - detail::shutdown_socket(sock); - detail::close_socket(sock); - } - } - - task_queue->shutdown(); - } - - is_decommissioned = !ret; - return ret; - } - - inline bool Server::routing(Request& req, Response& res, Stream& strm) { - if (pre_routing_handler_ && pre_routing_handler_(req, res) == HandlerResponse::Handled) { - return true; - } - - // File handler - if ((req.method == "GET" || req.method == "HEAD") && handle_file_request(req, res)) { - return true; - } - - if (detail::expect_content(req)) { - // Content reader handler - { - ContentReader reader( - [&](ContentReceiver receiver) { - auto result = read_content_with_content_receiver( - strm, req, res, std::move(receiver), nullptr, nullptr); - if (!result) { - output_error_log(Error::Read, &req); - } - return result; - }, - [&](FormDataHeader header, ContentReceiver receiver) { - auto result = read_content_with_content_receiver( - strm, req, res, nullptr, std::move(header), std::move(receiver)); - if (!result) { - output_error_log(Error::Read, &req); - } - return result; - }); - - if (req.method == "POST") { - if (dispatch_request_for_content_reader(req, res, std::move(reader), - post_handlers_for_content_reader_)) { - return true; - } - } else if (req.method == "PUT") { - if (dispatch_request_for_content_reader(req, res, std::move(reader), - put_handlers_for_content_reader_)) { - return true; - } - } else if (req.method == "PATCH") { - if (dispatch_request_for_content_reader(req, res, std::move(reader), - patch_handlers_for_content_reader_)) { - return true; - } - } else if (req.method == "DELETE") { - if (dispatch_request_for_content_reader(req, res, std::move(reader), - delete_handlers_for_content_reader_)) { - return true; - } - } - } - - // Read content into `req.body` - if (!read_content(strm, req, res)) { - output_error_log(Error::Read, &req); - return false; - } - } - - // Regular handler - if (req.method == "GET" || req.method == "HEAD") { - return dispatch_request(req, res, get_handlers_); - } else if (req.method == "POST") { - return dispatch_request(req, res, post_handlers_); - } else if (req.method == "PUT") { - return dispatch_request(req, res, put_handlers_); - } else if (req.method == "DELETE") { - return dispatch_request(req, res, delete_handlers_); - } else if (req.method == "OPTIONS") { - return dispatch_request(req, res, options_handlers_); - } else if (req.method == "PATCH") { - return dispatch_request(req, res, patch_handlers_); - } - - res.status = StatusCode::BadRequest_400; - return false; - } - - inline bool Server::dispatch_request(Request& req, Response& res, - const Handlers& handlers) const { - for (const auto& x : handlers) { - const auto& matcher = x.first; - const auto& handler = x.second; - - if (matcher->match(req)) { - req.matched_route = matcher->pattern(); - if (!pre_request_handler_ || - pre_request_handler_(req, res) != HandlerResponse::Handled) { - handler(req, res); - } - return true; - } - } - return false; - } - - inline void Server::apply_ranges(const Request& req, Response& res, std::string& content_type, - std::string& boundary) const { - if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) { - auto it = res.headers.find("Content-Type"); - if (it != res.headers.end()) { - content_type = it->second; - res.headers.erase(it); - } - - boundary = detail::make_multipart_data_boundary(); - - res.set_header("Content-Type", "multipart/byteranges; boundary=" + boundary); - } - - auto type = detail::encoding_type(req, res); - - if (res.body.empty()) { - if (res.content_length_ > 0) { - size_t length = 0; - if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) { - length = res.content_length_; - } else if (req.ranges.size() == 1) { - auto offset_and_length = - detail::get_range_offset_and_length(req.ranges[0], res.content_length_); - - length = offset_and_length.second; - - auto content_range = detail::make_content_range_header_field( - offset_and_length, res.content_length_); - res.set_header("Content-Range", content_range); - } else { - length = detail::get_multipart_ranges_data_length(req, boundary, content_type, - res.content_length_); - } - res.set_header("Content-Length", std::to_string(length)); - } else { - if (res.content_provider_) { - if (res.is_chunked_content_provider_) { - res.set_header("Transfer-Encoding", "chunked"); - if (type == detail::EncodingType::Gzip) { - res.set_header("Content-Encoding", "gzip"); - } else if (type == detail::EncodingType::Brotli) { - res.set_header("Content-Encoding", "br"); - } else if (type == detail::EncodingType::Zstd) { - res.set_header("Content-Encoding", "zstd"); - } - } - } - } - } else { - if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) { - ; - } else if (req.ranges.size() == 1) { - auto offset_and_length = - detail::get_range_offset_and_length(req.ranges[0], res.body.size()); - auto offset = offset_and_length.first; - auto length = offset_and_length.second; - - auto content_range = - detail::make_content_range_header_field(offset_and_length, res.body.size()); - res.set_header("Content-Range", content_range); - - assert(offset + length <= res.body.size()); - res.body = res.body.substr(offset, length); - } else { - std::string data; - detail::make_multipart_ranges_data(req, res, boundary, content_type, - res.body.size(), data); - res.body.swap(data); - } - - if (type != detail::EncodingType::None) { - output_pre_compression_log(req, res); - - std::unique_ptr compressor; - std::string content_encoding; - - if (type == detail::EncodingType::Gzip) { -#ifdef CPPHTTPLIB_ZLIB_SUPPORT - compressor = detail::make_unique(); - content_encoding = "gzip"; -#endif - } else if (type == detail::EncodingType::Brotli) { -#ifdef CPPHTTPLIB_BROTLI_SUPPORT - compressor = detail::make_unique(); - content_encoding = "br"; -#endif - } else if (type == detail::EncodingType::Zstd) { -#ifdef CPPHTTPLIB_ZSTD_SUPPORT - compressor = detail::make_unique(); - content_encoding = "zstd"; -#endif - } - - if (compressor) { - std::string compressed; - if (compressor->compress(res.body.data(), res.body.size(), true, - [&](const char* data, size_t data_len) { - compressed.append(data, data_len); - return true; - })) { - res.body.swap(compressed); - res.set_header("Content-Encoding", content_encoding); - } - } - } - - auto length = std::to_string(res.body.size()); - res.set_header("Content-Length", length); - } - } - - inline bool Server::dispatch_request_for_content_reader( - Request& req, Response& res, ContentReader content_reader, - const HandlersForContentReader& handlers) const { - for (const auto& x : handlers) { - const auto& matcher = x.first; - const auto& handler = x.second; - - if (matcher->match(req)) { - req.matched_route = matcher->pattern(); - if (!pre_request_handler_ || - pre_request_handler_(req, res) != HandlerResponse::Handled) { - handler(req, res, content_reader); - } - return true; - } - } - return false; - } - - inline std::string get_client_ip(const std::string& x_forwarded_for, - const std::vector& trusted_proxies) { - // X-Forwarded-For is a comma-separated list per RFC 7239 - std::vector ip_list; - detail::split(x_forwarded_for.data(), x_forwarded_for.data() + x_forwarded_for.size(), ',', - [&](const char* b, const char* e) { - auto r = detail::trim(b, e, 0, static_cast(e - b)); - ip_list.emplace_back(std::string(b + r.first, b + r.second)); - }); - - for (size_t i = 0; i < ip_list.size(); ++i) { - auto ip = ip_list[i]; - - auto is_trusted_proxy = - std::any_of(trusted_proxies.begin(), trusted_proxies.end(), - [&](const std::string& proxy) { return ip == proxy; }); - - if (is_trusted_proxy) { - if (i == 0) { - // If the trusted proxy is the first IP, there's no preceding client IP - return ip; - } else { - // Return the IP immediately before the trusted proxy - return ip_list[i - 1]; - } - } - } - - // If no trusted proxy is found, return the first IP in the list - return ip_list.front(); - } - - inline bool Server::process_request(Stream& strm, const std::string& remote_addr, - int remote_port, const std::string& local_addr, - int local_port, bool close_connection, - bool& connection_closed, - const std::function& setup_request) { - std::array buf{}; - - detail::stream_line_reader line_reader(strm, buf.data(), buf.size()); - - // Connection has been closed on client - if (!line_reader.getline()) { - return false; - } - - Request req; - req.start_time_ = std::chrono::steady_clock::now(); - - Response res; - res.version = "HTTP/1.1"; - res.headers = default_headers_; - -#ifdef __APPLE__ - // Socket file descriptor exceeded FD_SETSIZE... - if (strm.socket() >= FD_SETSIZE) { - Headers dummy; - detail::read_headers(strm, dummy); - res.status = StatusCode::InternalServerError_500; - output_error_log(Error::ExceedMaxSocketDescriptorCount, &req); - return write_response(strm, close_connection, req, res); - } -#endif - - // Request line and headers - if (!parse_request_line(line_reader.ptr(), req)) { - res.status = StatusCode::BadRequest_400; - output_error_log(Error::InvalidRequestLine, &req); - return write_response(strm, close_connection, req, res); - } - - // Request headers - if (!detail::read_headers(strm, req.headers)) { - res.status = StatusCode::BadRequest_400; - output_error_log(Error::InvalidHeaders, &req); - return write_response(strm, close_connection, req, res); - } - - // Check if the request URI doesn't exceed the limit - if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) { - res.status = StatusCode::UriTooLong_414; - output_error_log(Error::ExceedUriMaxLength, &req); - return write_response(strm, close_connection, req, res); - } - - if (req.get_header_value("Connection") == "close") { - connection_closed = true; - } - - if (req.version == "HTTP/1.0" && req.get_header_value("Connection") != "Keep-Alive") { - connection_closed = true; - } - - if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) { - auto x_forwarded_for = req.get_header_value("X-Forwarded-For"); - req.remote_addr = get_client_ip(x_forwarded_for, trusted_proxies_); - } else { - req.remote_addr = remote_addr; - } - req.remote_port = remote_port; - - req.local_addr = local_addr; - req.local_port = local_port; - - if (req.has_header("Accept")) { - const auto& accept_header = req.get_header_value("Accept"); - if (!detail::parse_accept_header(accept_header, req.accept_content_types)) { - res.status = StatusCode::BadRequest_400; - output_error_log(Error::HTTPParsing, &req); - return write_response(strm, close_connection, req, res); - } - } - - if (req.has_header("Range")) { - const auto& range_header_value = req.get_header_value("Range"); - if (!detail::parse_range_header(range_header_value, req.ranges)) { - res.status = StatusCode::RangeNotSatisfiable_416; - output_error_log(Error::InvalidRangeHeader, &req); - return write_response(strm, close_connection, req, res); - } - } - - if (setup_request) { - setup_request(req); - } - - if (req.get_header_value("Expect") == "100-continue") { - int status = StatusCode::Continue_100; - if (expect_100_continue_handler_) { - status = expect_100_continue_handler_(req, res); - } - switch (status) { - case StatusCode::Continue_100: - case StatusCode::ExpectationFailed_417: - detail::write_response_line(strm, status); - strm.write("\r\n"); - break; - default: - connection_closed = true; - return write_response(strm, true, req, res); - } - } - - // Setup `is_connection_closed` method - auto sock = strm.socket(); - req.is_connection_closed = [sock]() { return !detail::is_socket_alive(sock); }; - - // Routing - auto routed = false; -#ifdef CPPHTTPLIB_NO_EXCEPTIONS - routed = routing(req, res, strm); -#else - try { - routed = routing(req, res, strm); - } catch (std::exception& e) { - if (exception_handler_) { - auto ep = std::current_exception(); - exception_handler_(req, res, ep); - routed = true; - } else { - res.status = StatusCode::InternalServerError_500; - std::string val; - auto s = e.what(); - for (size_t i = 0; s[i]; i++) { - switch (s[i]) { - case '\r': - val += "\\r"; - break; - case '\n': - val += "\\n"; - break; - default: - val += s[i]; - break; - } - } - res.set_header("EXCEPTION_WHAT", val); - } - } catch (...) { - if (exception_handler_) { - auto ep = std::current_exception(); - exception_handler_(req, res, ep); - routed = true; - } else { - res.status = StatusCode::InternalServerError_500; - res.set_header("EXCEPTION_WHAT", "UNKNOWN"); - } - } -#endif - if (routed) { - if (res.status == -1) { - res.status = - req.ranges.empty() ? StatusCode::OK_200 : StatusCode::PartialContent_206; - } - - // Serve file content by using a content provider - if (!res.file_content_path_.empty()) { - const auto& path = res.file_content_path_; - auto mm = std::make_shared(path.c_str()); - if (!mm->is_open()) { - res.body.clear(); - res.content_length_ = 0; - res.content_provider_ = nullptr; - res.status = StatusCode::NotFound_404; - output_error_log(Error::OpenFile, &req); - return write_response(strm, close_connection, req, res); - } - - auto content_type = res.file_content_content_type_; - if (content_type.empty()) { - content_type = detail::find_content_type(path, file_extension_and_mimetype_map_, - default_file_mimetype_); - } - - res.set_content_provider( - mm->size(), content_type, - [mm](size_t offset, size_t length, DataSink& sink) -> bool { - sink.write(mm->data() + offset, length); - return true; - }); - } - - if (detail::range_error(req, res)) { - res.body.clear(); - res.content_length_ = 0; - res.content_provider_ = nullptr; - res.status = StatusCode::RangeNotSatisfiable_416; - return write_response(strm, close_connection, req, res); - } - - return write_response_with_content(strm, close_connection, req, res); - } else { - if (res.status == -1) { - res.status = StatusCode::NotFound_404; - } - - return write_response(strm, close_connection, req, res); - } - } - - inline bool Server::is_valid() const { return true; } - - inline bool Server::process_and_close_socket(socket_t sock) { - std::string remote_addr; - int remote_port = 0; - detail::get_remote_ip_and_port(sock, remote_addr, remote_port); - - std::string local_addr; - int local_port = 0; - detail::get_local_ip_and_port(sock, local_addr, local_port); - - auto ret = detail::process_server_socket( - svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_, read_timeout_sec_, - read_timeout_usec_, write_timeout_sec_, write_timeout_usec_, - [&](Stream& strm, bool close_connection, bool& connection_closed) { - return process_request(strm, remote_addr, remote_port, local_addr, local_port, - close_connection, connection_closed, nullptr); - }); - - detail::shutdown_socket(sock); - detail::close_socket(sock); - return ret; - } - - inline void Server::output_log(const Request& req, const Response& res) const { - if (logger_) { - std::lock_guard guard(logger_mutex_); - logger_(req, res); - } - } - - inline void Server::output_pre_compression_log(const Request& req, const Response& res) const { - if (pre_compression_logger_) { - std::lock_guard guard(logger_mutex_); - pre_compression_logger_(req, res); - } - } - - inline void Server::output_error_log(const Error& err, const Request* req) const { - if (error_logger_) { - std::lock_guard guard(logger_mutex_); - error_logger_(err, req); - } - } - - // HTTP client implementation - inline ClientImpl::ClientImpl(const std::string& host) - : ClientImpl(host, 80, std::string(), std::string()) {} - - inline ClientImpl::ClientImpl(const std::string& host, int port) - : ClientImpl(host, port, std::string(), std::string()) {} - - inline ClientImpl::ClientImpl(const std::string& host, int port, - const std::string& client_cert_path, - const std::string& client_key_path) - : host_(detail::escape_abstract_namespace_unix_domain(host)), - port_(port), - host_and_port_(detail::make_host_and_port_string(host_, port, is_ssl())), - client_cert_path_(client_cert_path), - client_key_path_(client_key_path) {} - - inline ClientImpl::~ClientImpl() { - // Wait until all the requests in flight are handled. - size_t retry_count = 10; - while (retry_count-- > 0) { - { - std::lock_guard guard(socket_mutex_); - if (socket_requests_in_flight_ == 0) { - break; - } - } - std::this_thread::sleep_for(std::chrono::milliseconds{1}); - } - - std::lock_guard guard(socket_mutex_); - shutdown_socket(socket_); - close_socket(socket_); - } - - inline bool ClientImpl::is_valid() const { return true; } - - inline void ClientImpl::copy_settings(const ClientImpl& rhs) { - client_cert_path_ = rhs.client_cert_path_; - client_key_path_ = rhs.client_key_path_; - connection_timeout_sec_ = rhs.connection_timeout_sec_; - read_timeout_sec_ = rhs.read_timeout_sec_; - read_timeout_usec_ = rhs.read_timeout_usec_; - write_timeout_sec_ = rhs.write_timeout_sec_; - write_timeout_usec_ = rhs.write_timeout_usec_; - max_timeout_msec_ = rhs.max_timeout_msec_; - basic_auth_username_ = rhs.basic_auth_username_; - basic_auth_password_ = rhs.basic_auth_password_; - bearer_token_auth_token_ = rhs.bearer_token_auth_token_; -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - digest_auth_username_ = rhs.digest_auth_username_; - digest_auth_password_ = rhs.digest_auth_password_; -#endif - keep_alive_ = rhs.keep_alive_; - follow_location_ = rhs.follow_location_; - path_encode_ = rhs.path_encode_; - address_family_ = rhs.address_family_; - tcp_nodelay_ = rhs.tcp_nodelay_; - ipv6_v6only_ = rhs.ipv6_v6only_; - socket_options_ = rhs.socket_options_; - compress_ = rhs.compress_; - decompress_ = rhs.decompress_; - interface_ = rhs.interface_; - proxy_host_ = rhs.proxy_host_; - proxy_port_ = rhs.proxy_port_; - proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_; - proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_; - proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_; -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_; - proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_; -#endif -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - ca_cert_file_path_ = rhs.ca_cert_file_path_; - ca_cert_dir_path_ = rhs.ca_cert_dir_path_; - ca_cert_store_ = rhs.ca_cert_store_; -#endif -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - server_certificate_verification_ = rhs.server_certificate_verification_; - server_hostname_verification_ = rhs.server_hostname_verification_; - server_certificate_verifier_ = rhs.server_certificate_verifier_; -#endif - logger_ = rhs.logger_; - error_logger_ = rhs.error_logger_; - } - - inline socket_t ClientImpl::create_client_socket(Error& error) const { - if (!proxy_host_.empty() && proxy_port_ != -1) { - return detail::create_client_socket( - proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_, - ipv6_v6only_, socket_options_, connection_timeout_sec_, connection_timeout_usec_, - read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, write_timeout_usec_, - interface_, error); - } - - // Check is custom IP specified for host_ - std::string ip; - auto it = addr_map_.find(host_); - if (it != addr_map_.end()) { - ip = it->second; - } - - return detail::create_client_socket( - host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_, socket_options_, - connection_timeout_sec_, connection_timeout_usec_, read_timeout_sec_, - read_timeout_usec_, write_timeout_sec_, write_timeout_usec_, interface_, error); - } - - inline bool ClientImpl::create_and_connect_socket(Socket& socket, Error& error) { - auto sock = create_client_socket(error); - if (sock == INVALID_SOCKET) { - return false; - } - socket.sock = sock; - return true; - } - - inline void ClientImpl::shutdown_ssl(Socket& /*socket*/, bool /*shutdown_gracefully*/) { - // If there are any requests in flight from threads other than us, then it's - // a thread-unsafe race because individual ssl* objects are not thread-safe. - assert(socket_requests_in_flight_ == 0 || - socket_requests_are_from_thread_ == std::this_thread::get_id()); - } - - inline void ClientImpl::shutdown_socket(Socket& socket) const { - if (socket.sock == INVALID_SOCKET) { - return; - } - detail::shutdown_socket(socket.sock); - } - - inline void ClientImpl::close_socket(Socket& socket) { - // If there are requests in flight in another thread, usually closing - // the socket will be fine and they will simply receive an error when - // using the closed socket, but it is still a bug since rarely the OS - // may reassign the socket id to be used for a new socket, and then - // suddenly they will be operating on a live socket that is different - // than the one they intended! - assert(socket_requests_in_flight_ == 0 || - socket_requests_are_from_thread_ == std::this_thread::get_id()); - - // It is also a bug if this happens while SSL is still active -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - assert(socket.ssl == nullptr); -#endif - if (socket.sock == INVALID_SOCKET) { - return; - } - detail::close_socket(socket.sock); - socket.sock = INVALID_SOCKET; - } - - inline bool ClientImpl::read_response_line(Stream& strm, const Request& req, - Response& res) const { - std::array buf{}; - - detail::stream_line_reader line_reader(strm, buf.data(), buf.size()); - - if (!line_reader.getline()) { - return false; - } - -#ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR - thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n"); -#else - thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n"); -#endif - - std::cmatch m; - if (!std::regex_match(line_reader.ptr(), m, re)) { - return req.method == "CONNECT"; - } - res.version = std::string(m[1]); - res.status = std::stoi(std::string(m[2])); - res.reason = std::string(m[3]); - - // Ignore '100 Continue' - while (res.status == StatusCode::Continue_100) { - if (!line_reader.getline()) { - return false; - } // CRLF - if (!line_reader.getline()) { - return false; - } // next response line - - if (!std::regex_match(line_reader.ptr(), m, re)) { - return false; - } - res.version = std::string(m[1]); - res.status = std::stoi(std::string(m[2])); - res.reason = std::string(m[3]); - } - - return true; - } - - inline bool ClientImpl::send(Request& req, Response& res, Error& error) { - std::lock_guard request_mutex_guard(request_mutex_); - auto ret = send_(req, res, error); - if (error == Error::SSLPeerCouldBeClosed_) { - assert(!ret); - ret = send_(req, res, error); - } - return ret; - } - - inline bool ClientImpl::send_(Request& req, Response& res, Error& error) { - { - std::lock_guard guard(socket_mutex_); - - // Set this to false immediately - if it ever gets set to true by the end - // of the request, we know another thread instructed us to close the - // socket. - socket_should_be_closed_when_request_is_done_ = false; - - auto is_alive = false; - if (socket_.is_open()) { - is_alive = detail::is_socket_alive(socket_.sock); - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - if (is_alive && is_ssl()) { - if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) { - is_alive = false; - } - } -#endif - - if (!is_alive) { - // Attempt to avoid sigpipe by shutting down non-gracefully if it - // seems like the other side has already closed the connection Also, - // there cannot be any requests in flight from other threads since we - // locked request_mutex_, so safe to close everything immediately - const bool shutdown_gracefully = false; - shutdown_ssl(socket_, shutdown_gracefully); - shutdown_socket(socket_); - close_socket(socket_); - } - } - - if (!is_alive) { - if (!create_and_connect_socket(socket_, error)) { - output_error_log(error, &req); - return false; - } - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - // TODO: refactoring - if (is_ssl()) { - auto& scli = static_cast(*this); - if (!proxy_host_.empty() && proxy_port_ != -1) { - auto success = false; - if (!scli.connect_with_proxy(socket_, req.start_time_, res, success, - error)) { - if (!success) { - output_error_log(error, &req); - } - return success; - } - } - - if (!scli.initialize_ssl(socket_, error)) { - output_error_log(error, &req); - return false; - } - } -#endif - } - - // Mark the current socket as being in use so that it cannot be closed by - // anyone else while this request is ongoing, even though we will be - // releasing the mutex. - if (socket_requests_in_flight_ > 1) { - assert(socket_requests_are_from_thread_ == std::this_thread::get_id()); - } - socket_requests_in_flight_ += 1; - socket_requests_are_from_thread_ = std::this_thread::get_id(); - } - - for (const auto& header : default_headers_) { - if (req.headers.find(header.first) == req.headers.end()) { - req.headers.insert(header); - } - } - - auto ret = false; - auto close_connection = !keep_alive_; - - auto se = detail::scope_exit([&]() { - // Briefly lock mutex in order to mark that a request is no longer ongoing - std::lock_guard guard(socket_mutex_); - socket_requests_in_flight_ -= 1; - if (socket_requests_in_flight_ <= 0) { - assert(socket_requests_in_flight_ == 0); - socket_requests_are_from_thread_ = std::thread::id(); - } - - if (socket_should_be_closed_when_request_is_done_ || close_connection || !ret) { - shutdown_ssl(socket_, true); - shutdown_socket(socket_); - close_socket(socket_); - } - }); - - ret = process_socket(socket_, req.start_time_, [&](Stream& strm) { - return handle_request(strm, req, res, close_connection, error); - }); - - if (!ret) { - if (error == Error::Success) { - error = Error::Unknown; - output_error_log(error, &req); - } - } - - return ret; - } - - inline Result ClientImpl::send(const Request& req) { - auto req2 = req; - return send_(std::move(req2)); - } - - inline Result ClientImpl::send_(Request&& req) { - auto res = detail::make_unique(); - auto error = Error::Success; - auto ret = send(req, *res, error); -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers), - last_ssl_error_, last_openssl_error_}; -#else - return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)}; -#endif - } - - inline bool ClientImpl::handle_request(Stream& strm, Request& req, Response& res, - bool close_connection, Error& error) { - if (req.path.empty()) { - error = Error::Connection; - output_error_log(error, &req); - return false; - } - - auto req_save = req; - - bool ret; - - if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) { - auto req2 = req; - req2.path = "http://" + host_and_port_ + req.path; - ret = process_request(strm, req2, res, close_connection, error); - req = req2; - req.path = req_save.path; - } else { - ret = process_request(strm, req, res, close_connection, error); - } - - if (!ret) { - return false; - } - - if (res.get_header_value("Connection") == "close" || - (res.version == "HTTP/1.0" && res.reason != "Connection established")) { - // TODO this requires a not-entirely-obvious chain of calls to be correct - // for this to be safe. - - // This is safe to call because handle_request is only called by send_ - // which locks the request mutex during the process. It would be a bug - // to call it from a different thread since it's a thread-safety issue - // to do these things to the socket if another thread is using the socket. - std::lock_guard guard(socket_mutex_); - shutdown_ssl(socket_, true); - shutdown_socket(socket_); - close_socket(socket_); - } - - if (300 < res.status && res.status < 400 && follow_location_) { - req = req_save; - ret = redirect(req, res, error); - } - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - if ((res.status == StatusCode::Unauthorized_401 || - res.status == StatusCode::ProxyAuthenticationRequired_407) && - req.authorization_count_ < 5) { - auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407; - const auto& username = is_proxy ? proxy_digest_auth_username_ : digest_auth_username_; - const auto& password = is_proxy ? proxy_digest_auth_password_ : digest_auth_password_; - - if (!username.empty() && !password.empty()) { - std::map auth; - if (detail::parse_www_authenticate(res, auth, is_proxy)) { - Request new_req = req; - new_req.authorization_count_ += 1; - new_req.headers.erase(is_proxy ? "Proxy-Authorization" : "Authorization"); - new_req.headers.insert(detail::make_digest_authentication_header( - req, auth, new_req.authorization_count_, detail::random_string(10), - username, password, is_proxy)); - - Response new_res; - - ret = send(new_req, new_res, error); - if (ret) { - res = new_res; - } - } - } - } -#endif - - return ret; - } - - inline bool ClientImpl::redirect(Request& req, Response& res, Error& error) { - if (req.redirect_count_ == 0) { - error = Error::ExceedRedirectCount; - output_error_log(error, &req); - return false; - } - - auto location = res.get_header_value("location"); - if (location.empty()) { - return false; - } - - thread_local const std::regex re( - R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)"); - - std::smatch m; - if (!std::regex_match(location, m, re)) { - return false; - } - - auto scheme = is_ssl() ? "https" : "http"; - - auto next_scheme = m[1].str(); - auto next_host = m[2].str(); - if (next_host.empty()) { - next_host = m[3].str(); - } - auto port_str = m[4].str(); - auto next_path = m[5].str(); - auto next_query = m[6].str(); - - auto next_port = port_; - if (!port_str.empty()) { - next_port = std::stoi(port_str); - } else if (!next_scheme.empty()) { - next_port = next_scheme == "https" ? 443 : 80; - } - - if (next_scheme.empty()) { - next_scheme = scheme; - } - if (next_host.empty()) { - next_host = host_; - } - if (next_path.empty()) { - next_path = "/"; - } - - auto path = decode_query_component(next_path, true) + next_query; - - // Same host redirect - use current client - if (next_scheme == scheme && next_host == host_ && next_port == port_) { - return detail::redirect(*this, req, res, path, location, error); - } - - // Cross-host/scheme redirect - create new client with robust setup - return create_redirect_client(next_scheme, next_host, next_port, req, res, path, location, - error); - } - - // New method for robust redirect client creation - inline bool ClientImpl::create_redirect_client(const std::string& scheme, - const std::string& host, int port, Request& req, - Response& res, const std::string& path, - const std::string& location, Error& error) { - // Determine if we need SSL - auto need_ssl = (scheme == "https"); - - // Clean up request headers that are host/client specific - // Remove headers that should not be carried over to new host - auto headers_to_remove = - std::vector{"Host", "Proxy-Authorization", "Authorization"}; - - for (const auto& header_name : headers_to_remove) { - auto it = req.headers.find(header_name); - while (it != req.headers.end()) { - it = req.headers.erase(it); - it = req.headers.find(header_name); - } - } - - // Create appropriate client type and handle redirect - if (need_ssl) { -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - // Create SSL client for HTTPS redirect - SSLClient redirect_client(host, port); - - // Setup basic client configuration first - setup_redirect_client(redirect_client); - - // SSL-specific configuration for proxy environments - if (!proxy_host_.empty() && proxy_port_ != -1) { - // Critical: Disable SSL verification for proxy environments - redirect_client.enable_server_certificate_verification(false); - redirect_client.enable_server_hostname_verification(false); - } else { - // For direct SSL connections, copy SSL verification settings - redirect_client.enable_server_certificate_verification( - server_certificate_verification_); - redirect_client.enable_server_hostname_verification(server_hostname_verification_); - } - - // Handle CA certificate store and paths if available - if (ca_cert_store_ && X509_STORE_up_ref(ca_cert_store_)) { - redirect_client.set_ca_cert_store(ca_cert_store_); - } - if (!ca_cert_file_path_.empty()) { - redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_); - } - - // Client certificates are set through constructor for SSLClient - // NOTE: SSLClient constructor already takes client_cert_path and - // client_key_path so we need to create it properly if client certs are - // needed - - // Execute the redirect - return detail::redirect(redirect_client, req, res, path, location, error); -#else - // SSL not supported - set appropriate error - error = Error::SSLConnection; - output_error_log(error, &req); - return false; -#endif - } else { - // HTTP redirect - ClientImpl redirect_client(host, port); - - // Setup client with robust configuration - setup_redirect_client(redirect_client); - - // Execute the redirect - return detail::redirect(redirect_client, req, res, path, location, error); - } - } - - // New method for robust client setup (based on basic_manual_redirect.cpp - // logic) - template - inline void ClientImpl::setup_redirect_client(ClientType& client) { - // Copy basic settings first - client.set_connection_timeout(connection_timeout_sec_); - client.set_read_timeout(read_timeout_sec_, read_timeout_usec_); - client.set_write_timeout(write_timeout_sec_, write_timeout_usec_); - client.set_keep_alive(keep_alive_); - client.set_follow_location(true); // Enable redirects to handle multi-step redirects - client.set_path_encode(path_encode_); - client.set_compress(compress_); - client.set_decompress(decompress_); - - // Copy authentication settings BEFORE proxy setup - if (!basic_auth_username_.empty()) { - client.set_basic_auth(basic_auth_username_, basic_auth_password_); - } - if (!bearer_token_auth_token_.empty()) { - client.set_bearer_token_auth(bearer_token_auth_token_); - } -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - if (!digest_auth_username_.empty()) { - client.set_digest_auth(digest_auth_username_, digest_auth_password_); - } -#endif - - // Setup proxy configuration (CRITICAL ORDER - proxy must be set - // before proxy auth) - if (!proxy_host_.empty() && proxy_port_ != -1) { - // First set proxy host and port - client.set_proxy(proxy_host_, proxy_port_); - - // Then set proxy authentication (order matters!) - if (!proxy_basic_auth_username_.empty()) { - client.set_proxy_basic_auth(proxy_basic_auth_username_, proxy_basic_auth_password_); - } - if (!proxy_bearer_token_auth_token_.empty()) { - client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_); - } -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - if (!proxy_digest_auth_username_.empty()) { - client.set_proxy_digest_auth(proxy_digest_auth_username_, - proxy_digest_auth_password_); - } -#endif - } - - // Copy network and socket settings - client.set_address_family(address_family_); - client.set_tcp_nodelay(tcp_nodelay_); - client.set_ipv6_v6only(ipv6_v6only_); - if (socket_options_) { - client.set_socket_options(socket_options_); - } - if (!interface_.empty()) { - client.set_interface(interface_); - } - - // Copy logging and headers - if (logger_) { - client.set_logger(logger_); - } - if (error_logger_) { - client.set_error_logger(error_logger_); - } - - // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers - // Each new client should generate its own headers based on its target host - } - - inline bool ClientImpl::write_content_with_provider(Stream& strm, const Request& req, - Error& error) const { - auto is_shutting_down = []() { return false; }; - - if (req.is_chunked_content_provider_) { - // TODO: Brotli support - std::unique_ptr compressor; -#ifdef CPPHTTPLIB_ZLIB_SUPPORT - if (compress_) { - compressor = detail::make_unique(); - } else -#endif - { - compressor = detail::make_unique(); - } - - return detail::write_content_chunked(strm, req.content_provider_, is_shutting_down, - *compressor, error); - } else { - return detail::write_content_with_progress(strm, req.content_provider_, 0, - req.content_length_, is_shutting_down, - req.upload_progress, error); - } - } - - inline bool ClientImpl::write_request(Stream& strm, Request& req, bool close_connection, - Error& error) { - // Prepare additional headers - if (close_connection) { - if (!req.has_header("Connection")) { - req.set_header("Connection", "close"); - } - } - - if (!req.has_header("Host")) { - // For Unix socket connections, use "localhost" as Host header (similar to - // curl behavior) - if (address_family_ == AF_UNIX) { - req.set_header("Host", "localhost"); - } else { - req.set_header("Host", host_and_port_); - } - } - - if (!req.has_header("Accept")) { - req.set_header("Accept", "*/*"); - } - - if (!req.content_receiver) { - if (!req.has_header("Accept-Encoding")) { - std::string accept_encoding; -#ifdef CPPHTTPLIB_BROTLI_SUPPORT - accept_encoding = "br"; -#endif -#ifdef CPPHTTPLIB_ZLIB_SUPPORT - if (!accept_encoding.empty()) { - accept_encoding += ", "; - } - accept_encoding += "gzip, deflate"; -#endif -#ifdef CPPHTTPLIB_ZSTD_SUPPORT - if (!accept_encoding.empty()) { - accept_encoding += ", "; - } - accept_encoding += "zstd"; -#endif - req.set_header("Accept-Encoding", accept_encoding); - } - -#ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT - if (!req.has_header("User-Agent")) { - auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION; - req.set_header("User-Agent", agent); - } -#endif - }; - - if (req.body.empty()) { - if (req.content_provider_) { - if (!req.is_chunked_content_provider_) { - if (!req.has_header("Content-Length")) { - auto length = std::to_string(req.content_length_); - req.set_header("Content-Length", length); - } - } - } else { - if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH") { - req.set_header("Content-Length", "0"); - } - } - } else { - if (!req.has_header("Content-Type")) { - req.set_header("Content-Type", "text/plain"); - } - - if (!req.has_header("Content-Length")) { - auto length = std::to_string(req.body.size()); - req.set_header("Content-Length", length); - } - } - - if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) { - if (!req.has_header("Authorization")) { - req.headers.insert(make_basic_authentication_header(basic_auth_username_, - basic_auth_password_, false)); - } - } - - if (!proxy_basic_auth_username_.empty() && !proxy_basic_auth_password_.empty()) { - if (!req.has_header("Proxy-Authorization")) { - req.headers.insert(make_basic_authentication_header( - proxy_basic_auth_username_, proxy_basic_auth_password_, true)); - } - } - - if (!bearer_token_auth_token_.empty()) { - if (!req.has_header("Authorization")) { - req.headers.insert( - make_bearer_token_authentication_header(bearer_token_auth_token_, false)); - } - } - - if (!proxy_bearer_token_auth_token_.empty()) { - if (!req.has_header("Proxy-Authorization")) { - req.headers.insert( - make_bearer_token_authentication_header(proxy_bearer_token_auth_token_, true)); - } - } - - // Request line and headers - { - detail::BufferStream bstrm; - - // Extract path and query from req.path - std::string path_part, query_part; - auto query_pos = req.path.find('?'); - if (query_pos != std::string::npos) { - path_part = req.path.substr(0, query_pos); - query_part = req.path.substr(query_pos + 1); - } else { - path_part = req.path; - query_part = ""; - } - - // Encode path and query - auto path_with_query = path_encode_ ? detail::encode_path(path_part) : path_part; - - detail::parse_query_text(query_part, req.params); - if (!req.params.empty()) { - path_with_query = append_query_params(path_with_query, req.params); - } - - // Write request line and headers - detail::write_request_line(bstrm, req.method, path_with_query); - header_writer_(bstrm, req.headers); - - // Flush buffer - auto& data = bstrm.get_buffer(); - if (!detail::write_data(strm, data.data(), data.size())) { - error = Error::Write; - output_error_log(error, &req); - return false; - } - } - - // Body - if (req.body.empty()) { - return write_content_with_provider(strm, req, error); - } - - if (req.upload_progress) { - auto body_size = req.body.size(); - size_t written = 0; - auto data = req.body.data(); - - while (written < body_size) { - size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written); - if (!detail::write_data(strm, data + written, to_write)) { - error = Error::Write; - output_error_log(error, &req); - return false; - } - written += to_write; - - if (!req.upload_progress(written, body_size)) { - error = Error::Canceled; - output_error_log(error, &req); - return false; - } - } - } else { - if (!detail::write_data(strm, req.body.data(), req.body.size())) { - error = Error::Write; - output_error_log(error, &req); - return false; - } - } - - return true; - } - - inline std::unique_ptr ClientImpl::send_with_content_provider_and_receiver( - Request& req, const char* body, size_t content_length, ContentProvider content_provider, - ContentProviderWithoutLength content_provider_without_length, - const std::string& content_type, ContentReceiver content_receiver, Error& error) { - if (!content_type.empty()) { - req.set_header("Content-Type", content_type); - } - -#ifdef CPPHTTPLIB_ZLIB_SUPPORT - if (compress_) { - req.set_header("Content-Encoding", "gzip"); - } -#endif - -#ifdef CPPHTTPLIB_ZLIB_SUPPORT - if (compress_ && !content_provider_without_length) { - // TODO: Brotli support - detail::gzip_compressor compressor; - - if (content_provider) { - auto ok = true; - size_t offset = 0; - DataSink data_sink; - - data_sink.write = [&](const char* data, size_t data_len) -> bool { - if (ok) { - auto last = offset + data_len == content_length; - - auto ret = compressor.compress( - data, data_len, last, - [&](const char* compressed_data, size_t compressed_data_len) { - req.body.append(compressed_data, compressed_data_len); - return true; - }); - - if (ret) { - offset += data_len; - } else { - ok = false; - } - } - return ok; - }; - - while (ok && offset < content_length) { - if (!content_provider(offset, content_length - offset, data_sink)) { - error = Error::Canceled; - output_error_log(error, &req); - return nullptr; - } - } - } else { - if (!compressor.compress(body, content_length, true, - [&](const char* data, size_t data_len) { - req.body.append(data, data_len); - return true; - })) { - error = Error::Compression; - output_error_log(error, &req); - return nullptr; - } - } - } else -#endif - { - if (content_provider) { - req.content_length_ = content_length; - req.content_provider_ = std::move(content_provider); - req.is_chunked_content_provider_ = false; - } else if (content_provider_without_length) { - req.content_length_ = 0; - req.content_provider_ = - detail::ContentProviderAdapter(std::move(content_provider_without_length)); - req.is_chunked_content_provider_ = true; - req.set_header("Transfer-Encoding", "chunked"); - } else { - req.body.assign(body, content_length); - } - } - - if (content_receiver) { - req.content_receiver = [content_receiver](const char* data, size_t data_length, - size_t /*offset*/, size_t /*total_length*/) { - return content_receiver(data, data_length); - }; - } - - auto res = detail::make_unique(); - return send(req, *res, error) ? std::move(res) : nullptr; - } - - inline Result ClientImpl::send_with_content_provider_and_receiver( - const std::string& method, const std::string& path, const Headers& headers, - const char* body, size_t content_length, ContentProvider content_provider, - ContentProviderWithoutLength content_provider_without_length, - const std::string& content_type, ContentReceiver content_receiver, - UploadProgress progress) { - Request req; - req.method = method; - req.headers = headers; - req.path = path; - req.upload_progress = std::move(progress); - if (max_timeout_msec_ > 0) { - req.start_time_ = std::chrono::steady_clock::now(); - } - - auto error = Error::Success; - - auto res = send_with_content_provider_and_receiver( - req, body, content_length, std::move(content_provider), - std::move(content_provider_without_length), content_type, std::move(content_receiver), - error); - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - return Result{std::move(res), error, std::move(req.headers), last_ssl_error_, - last_openssl_error_}; -#else - return Result{std::move(res), error, std::move(req.headers)}; -#endif - } - - inline void ClientImpl::output_log(const Request& req, const Response& res) const { - if (logger_) { - std::lock_guard guard(logger_mutex_); - logger_(req, res); - } - } - - inline void ClientImpl::output_error_log(const Error& err, const Request* req) const { - if (error_logger_) { - std::lock_guard guard(logger_mutex_); - error_logger_(err, req); - } - } - - inline bool ClientImpl::process_request(Stream& strm, Request& req, Response& res, - bool close_connection, Error& error) { - // Send request - if (!write_request(strm, req, close_connection, error)) { - return false; - } - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - if (is_ssl()) { - auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1; - if (!is_proxy_enabled) { - if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) { - error = Error::SSLPeerCouldBeClosed_; - output_error_log(error, &req); - return false; - } - } - } -#endif - - // Receive response and headers - if (!read_response_line(strm, req, res) || !detail::read_headers(strm, res.headers)) { - error = Error::Read; - output_error_log(error, &req); - return false; - } - - // Body - if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" && - req.method != "CONNECT") { - auto redirect = 300 < res.status && res.status < 400 && - res.status != StatusCode::NotModified_304 && follow_location_; - - if (req.response_handler && !redirect) { - if (!req.response_handler(res)) { - error = Error::Canceled; - output_error_log(error, &req); - return false; - } - } - - auto out = req.content_receiver - ? static_cast( - [&](const char* buf, size_t n, size_t off, size_t len) { - if (redirect) { - return true; - } - auto ret = req.content_receiver(buf, n, off, len); - if (!ret) { - error = Error::Canceled; - output_error_log(error, &req); - } - return ret; - }) - : static_cast( - [&](const char* buf, size_t n, size_t /*off*/, size_t /*len*/) { - assert(res.body.size() + n <= res.body.max_size()); - res.body.append(buf, n); - return true; - }); - - auto progress = [&](size_t current, size_t total) { - if (!req.download_progress || redirect) { - return true; - } - auto ret = req.download_progress(current, total); - if (!ret) { - error = Error::Canceled; - output_error_log(error, &req); - } - return ret; - }; - - if (res.has_header("Content-Length")) { - if (!req.content_receiver) { - auto len = res.get_header_value_u64("Content-Length"); - if (len > res.body.max_size()) { - error = Error::Read; - output_error_log(error, &req); - return false; - } - res.body.reserve(static_cast(len)); - } - } - - if (res.status != StatusCode::NotModified_304) { - int dummy_status; - if (!detail::read_content(strm, res, (std::numeric_limits::max)(), - dummy_status, std::move(progress), std::move(out), - decompress_)) { - if (error != Error::Canceled) { - error = Error::Read; - } - output_error_log(error, &req); - return false; - } - } - } - - // Log - output_log(req, res); - - return true; - } - - inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider( - const std::string& boundary, const UploadFormDataItems& items, - const FormDataProviderItems& provider_items) const { - size_t cur_item = 0; - size_t cur_start = 0; - // cur_item and cur_start are copied to within the std::function and - // maintain state between successive calls - return [&, cur_item, cur_start](size_t offset, DataSink& sink) mutable -> bool { - if (!offset && !items.empty()) { - sink.os << detail::serialize_multipart_formdata(items, boundary, false); - return true; - } else if (cur_item < provider_items.size()) { - if (!cur_start) { - const auto& begin = detail::serialize_multipart_formdata_item_begin( - provider_items[cur_item], boundary); - offset += begin.size(); - cur_start = offset; - sink.os << begin; - } - - DataSink cur_sink; - auto has_data = true; - cur_sink.write = sink.write; - cur_sink.done = [&]() { has_data = false; }; - - if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) { - return false; - } - - if (!has_data) { - sink.os << detail::serialize_multipart_formdata_item_end(); - cur_item++; - cur_start = 0; - } - return true; - } else { - sink.os << detail::serialize_multipart_formdata_finish(boundary); - sink.done(); - return true; - } - }; - } - - inline bool ClientImpl::process_socket( - const Socket& socket, std::chrono::time_point start_time, - std::function callback) { - return detail::process_client_socket(socket.sock, read_timeout_sec_, read_timeout_usec_, - write_timeout_sec_, write_timeout_usec_, - max_timeout_msec_, start_time, std::move(callback)); - } - - inline bool ClientImpl::is_ssl() const { return false; } - - inline Result ClientImpl::Get(const std::string& path, DownloadProgress progress) { - return Get(path, Headers(), std::move(progress)); - } - - inline Result ClientImpl::Get(const std::string& path, const Params& params, - const Headers& headers, DownloadProgress progress) { - if (params.empty()) { - return Get(path, headers); - } - - std::string path_with_query = append_query_params(path, params); - return Get(path_with_query, headers, std::move(progress)); - } - - inline Result ClientImpl::Get(const std::string& path, const Headers& headers, - DownloadProgress progress) { - Request req; - req.method = "GET"; - req.path = path; - req.headers = headers; - req.download_progress = std::move(progress); - if (max_timeout_msec_ > 0) { - req.start_time_ = std::chrono::steady_clock::now(); - } - - return send_(std::move(req)); - } - - inline Result ClientImpl::Get(const std::string& path, ContentReceiver content_receiver, - DownloadProgress progress) { - return Get(path, Headers(), nullptr, std::move(content_receiver), std::move(progress)); - } - - inline Result ClientImpl::Get(const std::string& path, const Headers& headers, - ContentReceiver content_receiver, DownloadProgress progress) { - return Get(path, headers, nullptr, std::move(content_receiver), std::move(progress)); - } - - inline Result ClientImpl::Get(const std::string& path, ResponseHandler response_handler, - ContentReceiver content_receiver, DownloadProgress progress) { - return Get(path, Headers(), std::move(response_handler), std::move(content_receiver), - std::move(progress)); - } - - inline Result ClientImpl::Get(const std::string& path, const Headers& headers, - ResponseHandler response_handler, - ContentReceiver content_receiver, DownloadProgress progress) { - Request req; - req.method = "GET"; - req.path = path; - req.headers = headers; - req.response_handler = std::move(response_handler); - req.content_receiver = [content_receiver](const char* data, size_t data_length, - size_t /*offset*/, size_t /*total_length*/) { - return content_receiver(data, data_length); - }; - req.download_progress = std::move(progress); - if (max_timeout_msec_ > 0) { - req.start_time_ = std::chrono::steady_clock::now(); - } - - return send_(std::move(req)); - } - - inline Result ClientImpl::Get(const std::string& path, const Params& params, - const Headers& headers, ContentReceiver content_receiver, - DownloadProgress progress) { - return Get(path, params, headers, nullptr, std::move(content_receiver), - std::move(progress)); - } - - inline Result ClientImpl::Get(const std::string& path, const Params& params, - const Headers& headers, ResponseHandler response_handler, - ContentReceiver content_receiver, DownloadProgress progress) { - if (params.empty()) { - return Get(path, headers, std::move(response_handler), std::move(content_receiver), - std::move(progress)); - } - - std::string path_with_query = append_query_params(path, params); - return Get(path_with_query, headers, std::move(response_handler), - std::move(content_receiver), std::move(progress)); - } - - inline Result ClientImpl::Head(const std::string& path) { return Head(path, Headers()); } - - inline Result ClientImpl::Head(const std::string& path, const Headers& headers) { - Request req; - req.method = "HEAD"; - req.headers = headers; - req.path = path; - if (max_timeout_msec_ > 0) { - req.start_time_ = std::chrono::steady_clock::now(); - } - - return send_(std::move(req)); - } - - inline Result ClientImpl::Post(const std::string& path) { - return Post(path, std::string(), std::string()); - } - - inline Result ClientImpl::Post(const std::string& path, const Headers& headers) { - return Post(path, headers, nullptr, 0, std::string()); - } - - inline Result ClientImpl::Post(const std::string& path, const char* body, size_t content_length, - const std::string& content_type, UploadProgress progress) { - return Post(path, Headers(), body, content_length, content_type, progress); - } - - inline Result ClientImpl::Post(const std::string& path, const std::string& body, - const std::string& content_type, UploadProgress progress) { - return Post(path, Headers(), body, content_type, progress); - } - - inline Result ClientImpl::Post(const std::string& path, const Params& params) { - return Post(path, Headers(), params); - } - - inline Result ClientImpl::Post(const std::string& path, size_t content_length, - ContentProvider content_provider, - const std::string& content_type, UploadProgress progress) { - return Post(path, Headers(), content_length, std::move(content_provider), content_type, - progress); - } - - inline Result ClientImpl::Post(const std::string& path, size_t content_length, - ContentProvider content_provider, - const std::string& content_type, - ContentReceiver content_receiver, UploadProgress progress) { - return Post(path, Headers(), content_length, std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - - inline Result ClientImpl::Post(const std::string& path, - ContentProviderWithoutLength content_provider, - const std::string& content_type, UploadProgress progress) { - return Post(path, Headers(), std::move(content_provider), content_type, progress); - } - - inline Result ClientImpl::Post(const std::string& path, - ContentProviderWithoutLength content_provider, - const std::string& content_type, - ContentReceiver content_receiver, UploadProgress progress) { - return Post(path, Headers(), std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - - inline Result ClientImpl::Post(const std::string& path, const Headers& headers, - const Params& params) { - auto query = detail::params_to_query_str(params); - return Post(path, headers, query, "application/x-www-form-urlencoded"); - } - - inline Result ClientImpl::Post(const std::string& path, const UploadFormDataItems& items, - UploadProgress progress) { - return Post(path, Headers(), items, progress); - } - - inline Result ClientImpl::Post(const std::string& path, const Headers& headers, - const UploadFormDataItems& items, UploadProgress progress) { - const auto& boundary = detail::make_multipart_data_boundary(); - const auto& content_type = detail::serialize_multipart_formdata_get_content_type(boundary); - const auto& body = detail::serialize_multipart_formdata(items, boundary); - return Post(path, headers, body, content_type, progress); - } - - inline Result ClientImpl::Post(const std::string& path, const Headers& headers, - const UploadFormDataItems& items, const std::string& boundary, - UploadProgress progress) { - if (!detail::is_multipart_boundary_chars_valid(boundary)) { - return Result{nullptr, Error::UnsupportedMultipartBoundaryChars}; - } - - const auto& content_type = detail::serialize_multipart_formdata_get_content_type(boundary); - const auto& body = detail::serialize_multipart_formdata(items, boundary); - return Post(path, headers, body, content_type, progress); - } - - inline Result ClientImpl::Post(const std::string& path, const Headers& headers, - const char* body, size_t content_length, - const std::string& content_type, UploadProgress progress) { - return send_with_content_provider_and_receiver("POST", path, headers, body, content_length, - nullptr, nullptr, content_type, nullptr, - progress); - } - - inline Result ClientImpl::Post(const std::string& path, const Headers& headers, - const std::string& body, const std::string& content_type, - UploadProgress progress) { - return send_with_content_provider_and_receiver("POST", path, headers, body.data(), - body.size(), nullptr, nullptr, content_type, - nullptr, progress); - } - - inline Result ClientImpl::Post(const std::string& path, const Headers& headers, - size_t content_length, ContentProvider content_provider, - const std::string& content_type, UploadProgress progress) { - return send_with_content_provider_and_receiver("POST", path, headers, nullptr, - content_length, std::move(content_provider), - nullptr, content_type, nullptr, progress); - } - - inline Result ClientImpl::Post(const std::string& path, const Headers& headers, - size_t content_length, ContentProvider content_provider, - const std::string& content_type, - ContentReceiver content_receiver, DownloadProgress progress) { - return send_with_content_provider_and_receiver( - "POST", path, headers, nullptr, content_length, std::move(content_provider), nullptr, - content_type, std::move(content_receiver), std::move(progress)); - } - - inline Result ClientImpl::Post(const std::string& path, const Headers& headers, - ContentProviderWithoutLength content_provider, - const std::string& content_type, UploadProgress progress) { - return send_with_content_provider_and_receiver("POST", path, headers, nullptr, 0, nullptr, - std::move(content_provider), content_type, - nullptr, progress); - } - - inline Result ClientImpl::Post(const std::string& path, const Headers& headers, - ContentProviderWithoutLength content_provider, - const std::string& content_type, - ContentReceiver content_receiver, DownloadProgress progress) { - return send_with_content_provider_and_receiver( - "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider), content_type, - std::move(content_receiver), std::move(progress)); - } - - inline Result ClientImpl::Post(const std::string& path, const Headers& headers, - const UploadFormDataItems& items, - const FormDataProviderItems& provider_items, - UploadProgress progress) { - const auto& boundary = detail::make_multipart_data_boundary(); - const auto& content_type = detail::serialize_multipart_formdata_get_content_type(boundary); - return send_with_content_provider_and_receiver( - "POST", path, headers, nullptr, 0, nullptr, - get_multipart_content_provider(boundary, items, provider_items), content_type, nullptr, - progress); - } - - inline Result ClientImpl::Post(const std::string& path, const Headers& headers, - const std::string& body, const std::string& content_type, - ContentReceiver content_receiver, DownloadProgress progress) { - Request req; - req.method = "POST"; - req.path = path; - req.headers = headers; - req.body = body; - req.content_receiver = [content_receiver](const char* data, size_t data_length, - size_t /*offset*/, size_t /*total_length*/) { - return content_receiver(data, data_length); - }; - req.download_progress = std::move(progress); - - if (max_timeout_msec_ > 0) { - req.start_time_ = std::chrono::steady_clock::now(); - } - - if (!content_type.empty()) { - req.set_header("Content-Type", content_type); - } - - return send_(std::move(req)); - } - - inline Result ClientImpl::Put(const std::string& path) { - return Put(path, std::string(), std::string()); - } - - inline Result ClientImpl::Put(const std::string& path, const Headers& headers) { - return Put(path, headers, nullptr, 0, std::string()); - } - - inline Result ClientImpl::Put(const std::string& path, const char* body, size_t content_length, - const std::string& content_type, UploadProgress progress) { - return Put(path, Headers(), body, content_length, content_type, progress); - } - - inline Result ClientImpl::Put(const std::string& path, const std::string& body, - const std::string& content_type, UploadProgress progress) { - return Put(path, Headers(), body, content_type, progress); - } - - inline Result ClientImpl::Put(const std::string& path, const Params& params) { - return Put(path, Headers(), params); - } - - inline Result ClientImpl::Put(const std::string& path, size_t content_length, - ContentProvider content_provider, const std::string& content_type, - UploadProgress progress) { - return Put(path, Headers(), content_length, std::move(content_provider), content_type, - progress); - } - - inline Result ClientImpl::Put(const std::string& path, size_t content_length, - ContentProvider content_provider, const std::string& content_type, - ContentReceiver content_receiver, UploadProgress progress) { - return Put(path, Headers(), content_length, std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - - inline Result ClientImpl::Put(const std::string& path, - ContentProviderWithoutLength content_provider, - const std::string& content_type, UploadProgress progress) { - return Put(path, Headers(), std::move(content_provider), content_type, progress); - } - - inline Result ClientImpl::Put(const std::string& path, - ContentProviderWithoutLength content_provider, - const std::string& content_type, ContentReceiver content_receiver, - UploadProgress progress) { - return Put(path, Headers(), std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - - inline Result ClientImpl::Put(const std::string& path, const Headers& headers, - const Params& params) { - auto query = detail::params_to_query_str(params); - return Put(path, headers, query, "application/x-www-form-urlencoded"); - } - - inline Result ClientImpl::Put(const std::string& path, const UploadFormDataItems& items, - UploadProgress progress) { - return Put(path, Headers(), items, progress); - } - - inline Result ClientImpl::Put(const std::string& path, const Headers& headers, - const UploadFormDataItems& items, UploadProgress progress) { - const auto& boundary = detail::make_multipart_data_boundary(); - const auto& content_type = detail::serialize_multipart_formdata_get_content_type(boundary); - const auto& body = detail::serialize_multipart_formdata(items, boundary); - return Put(path, headers, body, content_type, progress); - } - - inline Result ClientImpl::Put(const std::string& path, const Headers& headers, - const UploadFormDataItems& items, const std::string& boundary, - UploadProgress progress) { - if (!detail::is_multipart_boundary_chars_valid(boundary)) { - return Result{nullptr, Error::UnsupportedMultipartBoundaryChars}; - } - - const auto& content_type = detail::serialize_multipart_formdata_get_content_type(boundary); - const auto& body = detail::serialize_multipart_formdata(items, boundary); - return Put(path, headers, body, content_type, progress); - } - - inline Result ClientImpl::Put(const std::string& path, const Headers& headers, const char* body, - size_t content_length, const std::string& content_type, - UploadProgress progress) { - return send_with_content_provider_and_receiver("PUT", path, headers, body, content_length, - nullptr, nullptr, content_type, nullptr, - progress); - } - - inline Result ClientImpl::Put(const std::string& path, const Headers& headers, - const std::string& body, const std::string& content_type, - UploadProgress progress) { - return send_with_content_provider_and_receiver("PUT", path, headers, body.data(), - body.size(), nullptr, nullptr, content_type, - nullptr, progress); - } - - inline Result ClientImpl::Put(const std::string& path, const Headers& headers, - size_t content_length, ContentProvider content_provider, - const std::string& content_type, UploadProgress progress) { - return send_with_content_provider_and_receiver("PUT", path, headers, nullptr, - content_length, std::move(content_provider), - nullptr, content_type, nullptr, progress); - } - - inline Result ClientImpl::Put(const std::string& path, const Headers& headers, - size_t content_length, ContentProvider content_provider, - const std::string& content_type, ContentReceiver content_receiver, - UploadProgress progress) { - return send_with_content_provider_and_receiver( - "PUT", path, headers, nullptr, content_length, std::move(content_provider), nullptr, - content_type, std::move(content_receiver), progress); - } - - inline Result ClientImpl::Put(const std::string& path, const Headers& headers, - ContentProviderWithoutLength content_provider, - const std::string& content_type, UploadProgress progress) { - return send_with_content_provider_and_receiver("PUT", path, headers, nullptr, 0, nullptr, - std::move(content_provider), content_type, - nullptr, progress); - } - - inline Result ClientImpl::Put(const std::string& path, const Headers& headers, - ContentProviderWithoutLength content_provider, - const std::string& content_type, ContentReceiver content_receiver, - UploadProgress progress) { - return send_with_content_provider_and_receiver("PUT", path, headers, nullptr, 0, nullptr, - std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - - inline Result ClientImpl::Put(const std::string& path, const Headers& headers, - const UploadFormDataItems& items, - const FormDataProviderItems& provider_items, - UploadProgress progress) { - const auto& boundary = detail::make_multipart_data_boundary(); - const auto& content_type = detail::serialize_multipart_formdata_get_content_type(boundary); - return send_with_content_provider_and_receiver( - "PUT", path, headers, nullptr, 0, nullptr, - get_multipart_content_provider(boundary, items, provider_items), content_type, nullptr, - progress); - } - - inline Result ClientImpl::Put(const std::string& path, const Headers& headers, - const std::string& body, const std::string& content_type, - ContentReceiver content_receiver, DownloadProgress progress) { - Request req; - req.method = "PUT"; - req.path = path; - req.headers = headers; - req.body = body; - req.content_receiver = [content_receiver](const char* data, size_t data_length, - size_t /*offset*/, size_t /*total_length*/) { - return content_receiver(data, data_length); - }; - req.download_progress = std::move(progress); - - if (max_timeout_msec_ > 0) { - req.start_time_ = std::chrono::steady_clock::now(); - } - - if (!content_type.empty()) { - req.set_header("Content-Type", content_type); - } - - return send_(std::move(req)); - } - - inline Result ClientImpl::Patch(const std::string& path) { - return Patch(path, std::string(), std::string()); - } - - inline Result ClientImpl::Patch(const std::string& path, const Headers& headers, - UploadProgress progress) { - return Patch(path, headers, nullptr, 0, std::string(), progress); - } - - inline Result ClientImpl::Patch(const std::string& path, const char* body, - size_t content_length, const std::string& content_type, - UploadProgress progress) { - return Patch(path, Headers(), body, content_length, content_type, progress); - } - - inline Result ClientImpl::Patch(const std::string& path, const std::string& body, - const std::string& content_type, UploadProgress progress) { - return Patch(path, Headers(), body, content_type, progress); - } - - inline Result ClientImpl::Patch(const std::string& path, const Params& params) { - return Patch(path, Headers(), params); - } - - inline Result ClientImpl::Patch(const std::string& path, size_t content_length, - ContentProvider content_provider, - const std::string& content_type, UploadProgress progress) { - return Patch(path, Headers(), content_length, std::move(content_provider), content_type, - progress); - } - - inline Result ClientImpl::Patch(const std::string& path, size_t content_length, - ContentProvider content_provider, - const std::string& content_type, - ContentReceiver content_receiver, UploadProgress progress) { - return Patch(path, Headers(), content_length, std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - - inline Result ClientImpl::Patch(const std::string& path, - ContentProviderWithoutLength content_provider, - const std::string& content_type, UploadProgress progress) { - return Patch(path, Headers(), std::move(content_provider), content_type, progress); - } - - inline Result ClientImpl::Patch(const std::string& path, - ContentProviderWithoutLength content_provider, - const std::string& content_type, - ContentReceiver content_receiver, UploadProgress progress) { - return Patch(path, Headers(), std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - - inline Result ClientImpl::Patch(const std::string& path, const Headers& headers, - const Params& params) { - auto query = detail::params_to_query_str(params); - return Patch(path, headers, query, "application/x-www-form-urlencoded"); - } - - inline Result ClientImpl::Patch(const std::string& path, const UploadFormDataItems& items, - UploadProgress progress) { - return Patch(path, Headers(), items, progress); - } - - inline Result ClientImpl::Patch(const std::string& path, const Headers& headers, - const UploadFormDataItems& items, UploadProgress progress) { - const auto& boundary = detail::make_multipart_data_boundary(); - const auto& content_type = detail::serialize_multipart_formdata_get_content_type(boundary); - const auto& body = detail::serialize_multipart_formdata(items, boundary); - return Patch(path, headers, body, content_type, progress); - } - - inline Result ClientImpl::Patch(const std::string& path, const Headers& headers, - const UploadFormDataItems& items, const std::string& boundary, - UploadProgress progress) { - if (!detail::is_multipart_boundary_chars_valid(boundary)) { - return Result{nullptr, Error::UnsupportedMultipartBoundaryChars}; - } - - const auto& content_type = detail::serialize_multipart_formdata_get_content_type(boundary); - const auto& body = detail::serialize_multipart_formdata(items, boundary); - return Patch(path, headers, body, content_type, progress); - } - - inline Result ClientImpl::Patch(const std::string& path, const Headers& headers, - const char* body, size_t content_length, - const std::string& content_type, UploadProgress progress) { - return send_with_content_provider_and_receiver("PATCH", path, headers, body, content_length, - nullptr, nullptr, content_type, nullptr, - progress); - } - - inline Result ClientImpl::Patch(const std::string& path, const Headers& headers, - const std::string& body, const std::string& content_type, - UploadProgress progress) { - return send_with_content_provider_and_receiver("PATCH", path, headers, body.data(), - body.size(), nullptr, nullptr, content_type, - nullptr, progress); - } - - inline Result ClientImpl::Patch(const std::string& path, const Headers& headers, - size_t content_length, ContentProvider content_provider, - const std::string& content_type, UploadProgress progress) { - return send_with_content_provider_and_receiver("PATCH", path, headers, nullptr, - content_length, std::move(content_provider), - nullptr, content_type, nullptr, progress); - } - - inline Result ClientImpl::Patch(const std::string& path, const Headers& headers, - size_t content_length, ContentProvider content_provider, - const std::string& content_type, - ContentReceiver content_receiver, UploadProgress progress) { - return send_with_content_provider_and_receiver( - "PATCH", path, headers, nullptr, content_length, std::move(content_provider), nullptr, - content_type, std::move(content_receiver), progress); - } - - inline Result ClientImpl::Patch(const std::string& path, const Headers& headers, - ContentProviderWithoutLength content_provider, - const std::string& content_type, UploadProgress progress) { - return send_with_content_provider_and_receiver("PATCH", path, headers, nullptr, 0, nullptr, - std::move(content_provider), content_type, - nullptr, progress); - } - - inline Result ClientImpl::Patch(const std::string& path, const Headers& headers, - ContentProviderWithoutLength content_provider, - const std::string& content_type, - ContentReceiver content_receiver, UploadProgress progress) { - return send_with_content_provider_and_receiver("PATCH", path, headers, nullptr, 0, nullptr, - std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - - inline Result ClientImpl::Patch(const std::string& path, const Headers& headers, - const UploadFormDataItems& items, - const FormDataProviderItems& provider_items, - UploadProgress progress) { - const auto& boundary = detail::make_multipart_data_boundary(); - const auto& content_type = detail::serialize_multipart_formdata_get_content_type(boundary); - return send_with_content_provider_and_receiver( - "PATCH", path, headers, nullptr, 0, nullptr, - get_multipart_content_provider(boundary, items, provider_items), content_type, nullptr, - progress); - } - - inline Result ClientImpl::Patch(const std::string& path, const Headers& headers, - const std::string& body, const std::string& content_type, - ContentReceiver content_receiver, DownloadProgress progress) { - Request req; - req.method = "PATCH"; - req.path = path; - req.headers = headers; - req.body = body; - req.content_receiver = [content_receiver](const char* data, size_t data_length, - size_t /*offset*/, size_t /*total_length*/) { - return content_receiver(data, data_length); - }; - req.download_progress = std::move(progress); - - if (max_timeout_msec_ > 0) { - req.start_time_ = std::chrono::steady_clock::now(); - } - - if (!content_type.empty()) { - req.set_header("Content-Type", content_type); - } - - return send_(std::move(req)); - } - - inline Result ClientImpl::Delete(const std::string& path, DownloadProgress progress) { - return Delete(path, Headers(), std::string(), std::string(), progress); - } - - inline Result ClientImpl::Delete(const std::string& path, const Headers& headers, - DownloadProgress progress) { - return Delete(path, headers, std::string(), std::string(), progress); - } - - inline Result ClientImpl::Delete(const std::string& path, const char* body, - size_t content_length, const std::string& content_type, - DownloadProgress progress) { - return Delete(path, Headers(), body, content_length, content_type, progress); - } - - inline Result ClientImpl::Delete(const std::string& path, const std::string& body, - const std::string& content_type, DownloadProgress progress) { - return Delete(path, Headers(), body.data(), body.size(), content_type, progress); - } - - inline Result ClientImpl::Delete(const std::string& path, const Headers& headers, - const std::string& body, const std::string& content_type, - DownloadProgress progress) { - return Delete(path, headers, body.data(), body.size(), content_type, progress); - } - - inline Result ClientImpl::Delete(const std::string& path, const Params& params, - DownloadProgress progress) { - return Delete(path, Headers(), params, progress); - } - - inline Result ClientImpl::Delete(const std::string& path, const Headers& headers, - const Params& params, DownloadProgress progress) { - auto query = detail::params_to_query_str(params); - return Delete(path, headers, query, "application/x-www-form-urlencoded", progress); - } - - inline Result ClientImpl::Delete(const std::string& path, const Headers& headers, - const char* body, size_t content_length, - const std::string& content_type, DownloadProgress progress) { - Request req; - req.method = "DELETE"; - req.headers = headers; - req.path = path; - req.download_progress = std::move(progress); - if (max_timeout_msec_ > 0) { - req.start_time_ = std::chrono::steady_clock::now(); - } - - if (!content_type.empty()) { - req.set_header("Content-Type", content_type); - } - req.body.assign(body, content_length); - - return send_(std::move(req)); - } - - inline Result ClientImpl::Options(const std::string& path) { return Options(path, Headers()); } - - inline Result ClientImpl::Options(const std::string& path, const Headers& headers) { - Request req; - req.method = "OPTIONS"; - req.headers = headers; - req.path = path; - if (max_timeout_msec_ > 0) { - req.start_time_ = std::chrono::steady_clock::now(); - } - - return send_(std::move(req)); - } - - inline void ClientImpl::stop() { - std::lock_guard guard(socket_mutex_); - - // If there is anything ongoing right now, the ONLY thread-safe thing we can - // do is to shutdown_socket, so that threads using this socket suddenly - // discover they can't read/write any more and error out. Everything else - // (closing the socket, shutting ssl down) is unsafe because these actions - // are not thread-safe. - if (socket_requests_in_flight_ > 0) { - shutdown_socket(socket_); - - // Aside from that, we set a flag for the socket to be closed when we're - // done. - socket_should_be_closed_when_request_is_done_ = true; - return; - } - - // Otherwise, still holding the mutex, we can shut everything down ourselves - shutdown_ssl(socket_, true); - shutdown_socket(socket_); - close_socket(socket_); - } - - inline std::string ClientImpl::host() const { return host_; } - - inline int ClientImpl::port() const { return port_; } - - inline size_t ClientImpl::is_socket_open() const { - std::lock_guard guard(socket_mutex_); - return socket_.is_open(); - } - - inline socket_t ClientImpl::socket() const { return socket_.sock; } - - inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) { - connection_timeout_sec_ = sec; - connection_timeout_usec_ = usec; - } - - inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) { - read_timeout_sec_ = sec; - read_timeout_usec_ = usec; - } - - inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) { - write_timeout_sec_ = sec; - write_timeout_usec_ = usec; - } - - inline void ClientImpl::set_max_timeout(time_t msec) { max_timeout_msec_ = msec; } - - inline void ClientImpl::set_basic_auth(const std::string& username, - const std::string& password) { - basic_auth_username_ = username; - basic_auth_password_ = password; - } - - inline void ClientImpl::set_bearer_token_auth(const std::string& token) { - bearer_token_auth_token_ = token; - } - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - inline void ClientImpl::set_digest_auth(const std::string& username, - const std::string& password) { - digest_auth_username_ = username; - digest_auth_password_ = password; - } -#endif - - inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; } - - inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; } - - inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; } - - inline void ClientImpl::set_hostname_addr_map(std::map addr_map) { - addr_map_ = std::move(addr_map); - } - - inline void ClientImpl::set_default_headers(Headers headers) { - default_headers_ = std::move(headers); - } - - inline void ClientImpl::set_header_writer( - std::function const& writer) { - header_writer_ = writer; - } - - inline void ClientImpl::set_address_family(int family) { address_family_ = family; } - - inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; } - - inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; } - - inline void ClientImpl::set_socket_options(SocketOptions socket_options) { - socket_options_ = std::move(socket_options); - } - - inline void ClientImpl::set_compress(bool on) { compress_ = on; } - - inline void ClientImpl::set_decompress(bool on) { decompress_ = on; } - - inline void ClientImpl::set_interface(const std::string& intf) { interface_ = intf; } - - inline void ClientImpl::set_proxy(const std::string& host, int port) { - proxy_host_ = host; - proxy_port_ = port; - } - - inline void ClientImpl::set_proxy_basic_auth(const std::string& username, - const std::string& password) { - proxy_basic_auth_username_ = username; - proxy_basic_auth_password_ = password; - } - - inline void ClientImpl::set_proxy_bearer_token_auth(const std::string& token) { - proxy_bearer_token_auth_token_ = token; - } - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - inline void ClientImpl::set_proxy_digest_auth(const std::string& username, - const std::string& password) { - proxy_digest_auth_username_ = username; - proxy_digest_auth_password_ = password; - } - - inline void ClientImpl::set_ca_cert_path(const std::string& ca_cert_file_path, - const std::string& ca_cert_dir_path) { - ca_cert_file_path_ = ca_cert_file_path; - ca_cert_dir_path_ = ca_cert_dir_path; - } - - inline void ClientImpl::set_ca_cert_store(X509_STORE* ca_cert_store) { - if (ca_cert_store && ca_cert_store != ca_cert_store_) { - ca_cert_store_ = ca_cert_store; - } - } - - inline X509_STORE* ClientImpl::create_ca_cert_store(const char* ca_cert, - std::size_t size) const { - auto mem = BIO_new_mem_buf(ca_cert, static_cast(size)); - auto se = detail::scope_exit([&] { BIO_free_all(mem); }); - if (!mem) { - return nullptr; - } - - auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr); - if (!inf) { - return nullptr; - } - - auto cts = X509_STORE_new(); - if (cts) { - for (auto i = 0; i < static_cast(sk_X509_INFO_num(inf)); i++) { - auto itmp = sk_X509_INFO_value(inf, i); - if (!itmp) { - continue; - } - - if (itmp->x509) { - X509_STORE_add_cert(cts, itmp->x509); - } - if (itmp->crl) { - X509_STORE_add_crl(cts, itmp->crl); - } - } - } - - sk_X509_INFO_pop_free(inf, X509_INFO_free); - return cts; - } - - inline void ClientImpl::enable_server_certificate_verification(bool enabled) { - server_certificate_verification_ = enabled; - } - - inline void ClientImpl::enable_server_hostname_verification(bool enabled) { - server_hostname_verification_ = enabled; - } - - inline void ClientImpl::set_server_certificate_verifier( - std::function verifier) { - server_certificate_verifier_ = verifier; - } -#endif - - inline void ClientImpl::set_logger(Logger logger) { logger_ = std::move(logger); } - - inline void ClientImpl::set_error_logger(ErrorLogger error_logger) { - error_logger_ = std::move(error_logger); - } - -/* - * SSL Implementation - */ -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - namespace detail { - - inline bool is_ip_address(const std::string& host) { - struct in_addr addr4; - struct in6_addr addr6; - return inet_pton(AF_INET, host.c_str(), &addr4) == 1 || - inet_pton(AF_INET6, host.c_str(), &addr6) == 1; - } - - template - inline SSL* ssl_new(socket_t sock, SSL_CTX* ctx, std::mutex& ctx_mutex, - U SSL_connect_or_accept, V setup) { - SSL* ssl = nullptr; - { - std::lock_guard guard(ctx_mutex); - ssl = SSL_new(ctx); - } - - if (ssl) { - set_nonblocking(sock, true); - auto bio = BIO_new_socket(static_cast(sock), BIO_NOCLOSE); - BIO_set_nbio(bio, 1); - SSL_set_bio(ssl, bio, bio); - - if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) { - SSL_shutdown(ssl); - { - std::lock_guard guard(ctx_mutex); - SSL_free(ssl); - } - set_nonblocking(sock, false); - return nullptr; - } - BIO_set_nbio(bio, 0); - set_nonblocking(sock, false); - } - - return ssl; - } - - inline void ssl_delete(std::mutex& ctx_mutex, SSL* ssl, socket_t sock, - bool shutdown_gracefully) { - // sometimes we may want to skip this to try to avoid SIGPIPE if we know - // the remote has closed the network connection - // Note that it is not always possible to avoid SIGPIPE, this is merely a - // best-efforts. - if (shutdown_gracefully) { - (void)(sock); - // SSL_shutdown() returns 0 on first call (indicating close_notify alert - // sent) and 1 on subsequent call (indicating close_notify alert received) - if (SSL_shutdown(ssl) == 0) { - // Expected to return 1, but even if it doesn't, we free ssl - SSL_shutdown(ssl); - } - } - - std::lock_guard guard(ctx_mutex); - SSL_free(ssl); - } - - template - bool ssl_connect_or_accept_nonblocking(socket_t sock, SSL* ssl, U ssl_connect_or_accept, - time_t timeout_sec, time_t timeout_usec, - int* ssl_error) { - auto res = 0; - while ((res = ssl_connect_or_accept(ssl)) != 1) { - auto err = SSL_get_error(ssl, res); - switch (err) { - case SSL_ERROR_WANT_READ: - if (select_read(sock, timeout_sec, timeout_usec) > 0) { - continue; - } - break; - case SSL_ERROR_WANT_WRITE: - if (select_write(sock, timeout_sec, timeout_usec) > 0) { - continue; - } - break; - default: - break; - } - if (ssl_error) { - *ssl_error = err; - } - return false; - } - return true; - } - - template - inline bool process_server_socket_ssl(const std::atomic& svr_sock, SSL* ssl, - socket_t sock, size_t keep_alive_max_count, - time_t keep_alive_timeout_sec, - time_t read_timeout_sec, time_t read_timeout_usec, - time_t write_timeout_sec, time_t write_timeout_usec, - T callback) { - return process_server_socket_core( - svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec, - [&](bool close_connection, bool& connection_closed) { - SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec, - write_timeout_sec, write_timeout_usec); - return callback(strm, close_connection, connection_closed); - }); - } - - template - inline bool process_client_socket_ssl( - SSL* ssl, socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec, - time_t write_timeout_sec, time_t write_timeout_usec, time_t max_timeout_msec, - std::chrono::time_point start_time, T callback) { - SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec, write_timeout_sec, - write_timeout_usec, max_timeout_msec, start_time); - return callback(strm); - } - - // SSL socket stream implementation - inline SSLSocketStream::SSLSocketStream( - socket_t sock, SSL* ssl, time_t read_timeout_sec, time_t read_timeout_usec, - time_t write_timeout_sec, time_t write_timeout_usec, time_t max_timeout_msec, - std::chrono::time_point start_time) - : sock_(sock), - ssl_(ssl), - read_timeout_sec_(read_timeout_sec), - read_timeout_usec_(read_timeout_usec), - write_timeout_sec_(write_timeout_sec), - write_timeout_usec_(write_timeout_usec), - max_timeout_msec_(max_timeout_msec), - start_time_(start_time) { - SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY); - } - - inline SSLSocketStream::~SSLSocketStream() = default; - - inline bool SSLSocketStream::is_readable() const { return SSL_pending(ssl_) > 0; } - - inline bool SSLSocketStream::wait_readable() const { - if (max_timeout_msec_ <= 0) { - return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0; - } - - time_t read_timeout_sec; - time_t read_timeout_usec; - calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_, - read_timeout_usec_, read_timeout_sec, read_timeout_usec); - - return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0; - } - - inline bool SSLSocketStream::wait_writable() const { - return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 && - is_socket_alive(sock_) && !is_ssl_peer_could_be_closed(ssl_, sock_); - } - - inline ssize_t SSLSocketStream::read(char* ptr, size_t size) { - if (SSL_pending(ssl_) > 0) { - return SSL_read(ssl_, ptr, static_cast(size)); - } else if (wait_readable()) { - auto ret = SSL_read(ssl_, ptr, static_cast(size)); - if (ret < 0) { - auto err = SSL_get_error(ssl_, ret); - auto n = 1000; -#ifdef _WIN32 - while (--n >= 0 && - (err == SSL_ERROR_WANT_READ || - (err == SSL_ERROR_SYSCALL && WSAGetLastError() == WSAETIMEDOUT))) { -#else - while (--n >= 0 && err == SSL_ERROR_WANT_READ) { -#endif - if (SSL_pending(ssl_) > 0) { - return SSL_read(ssl_, ptr, static_cast(size)); - } else if (wait_readable()) { - std::this_thread::sleep_for(std::chrono::microseconds{10}); - ret = SSL_read(ssl_, ptr, static_cast(size)); - if (ret >= 0) { - return ret; - } - err = SSL_get_error(ssl_, ret); - } else { - break; - } - } - assert(ret < 0); - } - return ret; - } else { - return -1; - } - } - - inline ssize_t SSLSocketStream::write(const char* ptr, size_t size) { - if (wait_writable()) { - auto handle_size = - static_cast(std::min(size, (std::numeric_limits::max)())); - - auto ret = SSL_write(ssl_, ptr, static_cast(handle_size)); - if (ret < 0) { - auto err = SSL_get_error(ssl_, ret); - auto n = 1000; -#ifdef _WIN32 - while (--n >= 0 && - (err == SSL_ERROR_WANT_WRITE || - (err == SSL_ERROR_SYSCALL && WSAGetLastError() == WSAETIMEDOUT))) { -#else - while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) { -#endif - if (wait_writable()) { - std::this_thread::sleep_for(std::chrono::microseconds{10}); - ret = SSL_write(ssl_, ptr, static_cast(handle_size)); - if (ret >= 0) { - return ret; - } - err = SSL_get_error(ssl_, ret); - } else { - break; - } - } - assert(ret < 0); - } - return ret; - } - return -1; - } - - inline void SSLSocketStream::get_remote_ip_and_port(std::string& ip, int& port) const { - detail::get_remote_ip_and_port(sock_, ip, port); - } - - inline void SSLSocketStream::get_local_ip_and_port(std::string& ip, int& port) const { - detail::get_local_ip_and_port(sock_, ip, port); - } - - inline socket_t SSLSocketStream::socket() const { return sock_; } - - inline time_t SSLSocketStream::duration() const { - return std::chrono::duration_cast( - std::chrono::steady_clock::now() - start_time_) - .count(); - } - - } // namespace detail - - // SSL HTTP server implementation - inline SSLServer::SSLServer(const char* cert_path, const char* private_key_path, - const char* client_ca_cert_file_path, - const char* client_ca_cert_dir_path, - const char* private_key_password) { - ctx_ = SSL_CTX_new(TLS_server_method()); - - if (ctx_) { - SSL_CTX_set_options( - ctx_, SSL_OP_NO_COMPRESSION | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); - - SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION); - - if (private_key_password != nullptr && (private_key_password[0] != '\0')) { - SSL_CTX_set_default_passwd_cb_userdata( - ctx_, reinterpret_cast(const_cast(private_key_password))); - } - - if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 || - SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) != 1 || - SSL_CTX_check_private_key(ctx_) != 1) { - last_ssl_error_ = static_cast(ERR_get_error()); - SSL_CTX_free(ctx_); - ctx_ = nullptr; - } else if (client_ca_cert_file_path || client_ca_cert_dir_path) { - SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path, - client_ca_cert_dir_path); - - // Set client CA list to be sent to clients during TLS handshake - if (client_ca_cert_file_path) { - auto ca_list = SSL_load_client_CA_file(client_ca_cert_file_path); - if (ca_list != nullptr) { - SSL_CTX_set_client_CA_list(ctx_, ca_list); - } else { - // Failed to load client CA list, but we continue since - // SSL_CTX_load_verify_locations already succeeded and - // certificate verification will still work - last_ssl_error_ = static_cast(ERR_get_error()); - } - } - - SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, - nullptr); - } - } - } - - inline SSLServer::SSLServer(X509* cert, EVP_PKEY* private_key, - X509_STORE* client_ca_cert_store) { - ctx_ = SSL_CTX_new(TLS_server_method()); - - if (ctx_) { - SSL_CTX_set_options( - ctx_, SSL_OP_NO_COMPRESSION | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); - - SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION); - - if (SSL_CTX_use_certificate(ctx_, cert) != 1 || - SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) { - SSL_CTX_free(ctx_); - ctx_ = nullptr; - } else if (client_ca_cert_store) { - SSL_CTX_set_cert_store(ctx_, client_ca_cert_store); - - // Extract CA names from the store and set them as the client CA list - auto ca_list = extract_ca_names_from_x509_store(client_ca_cert_store); - if (ca_list) { - SSL_CTX_set_client_CA_list(ctx_, ca_list); - } else { - // Failed to extract CA names, record the error - last_ssl_error_ = static_cast(ERR_get_error()); - } - - SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, - nullptr); - } - } - } - - inline SSLServer::SSLServer( - const std::function& setup_ssl_ctx_callback) { - ctx_ = SSL_CTX_new(TLS_method()); - if (ctx_) { - if (!setup_ssl_ctx_callback(*ctx_)) { - SSL_CTX_free(ctx_); - ctx_ = nullptr; - } - } - } - - inline SSLServer::~SSLServer() { - if (ctx_) { - SSL_CTX_free(ctx_); - } - } - - inline bool SSLServer::is_valid() const { return ctx_; } - - inline SSL_CTX* SSLServer::ssl_context() const { return ctx_; } - - inline void SSLServer::update_certs(X509* cert, EVP_PKEY* private_key, - X509_STORE* client_ca_cert_store) { - std::lock_guard guard(ctx_mutex_); - - SSL_CTX_use_certificate(ctx_, cert); - SSL_CTX_use_PrivateKey(ctx_, private_key); - - if (client_ca_cert_store != nullptr) { - SSL_CTX_set_cert_store(ctx_, client_ca_cert_store); - } - } - - inline bool SSLServer::process_and_close_socket(socket_t sock) { - auto ssl = detail::ssl_new( - sock, ctx_, ctx_mutex_, - [&](SSL* ssl2) { - return detail::ssl_connect_or_accept_nonblocking( - sock, ssl2, SSL_accept, read_timeout_sec_, read_timeout_usec_, - &last_ssl_error_); - }, - [](SSL* /*ssl2*/) { return true; }); - - auto ret = false; - if (ssl) { - std::string remote_addr; - int remote_port = 0; - detail::get_remote_ip_and_port(sock, remote_addr, remote_port); - - std::string local_addr; - int local_port = 0; - detail::get_local_ip_and_port(sock, local_addr, local_port); - - ret = detail::process_server_socket_ssl( - svr_sock_, ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_, - read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, write_timeout_usec_, - [&](Stream& strm, bool close_connection, bool& connection_closed) { - return process_request(strm, remote_addr, remote_port, local_addr, local_port, - close_connection, connection_closed, - [&](Request& req) { req.ssl = ssl; }); - }); - - // Shutdown gracefully if the result seemed successful, non-gracefully if - // the connection appeared to be closed. - const bool shutdown_gracefully = ret; - detail::ssl_delete(ctx_mutex_, ssl, sock, shutdown_gracefully); - } - - detail::shutdown_socket(sock); - detail::close_socket(sock); - return ret; - } - - inline STACK_OF(X509_NAME) * SSLServer::extract_ca_names_from_x509_store(X509_STORE* store) { - if (!store) { - return nullptr; - } - - auto ca_list = sk_X509_NAME_new_null(); - if (!ca_list) { - return nullptr; - } - - // Get all objects from the store - auto objs = X509_STORE_get0_objects(store); - if (!objs) { - sk_X509_NAME_free(ca_list); - return nullptr; - } - - // Iterate through objects and extract certificate subject names - for (int i = 0; i < sk_X509_OBJECT_num(objs); i++) { - auto obj = sk_X509_OBJECT_value(objs, i); - if (X509_OBJECT_get_type(obj) == X509_LU_X509) { - auto cert = X509_OBJECT_get0_X509(obj); - if (cert) { - auto subject = X509_get_subject_name(cert); - if (subject) { - auto name_dup = X509_NAME_dup(subject); - if (name_dup) { - sk_X509_NAME_push(ca_list, name_dup); - } - } - } - } - } - - // If no names were extracted, free the list and return nullptr - if (sk_X509_NAME_num(ca_list) == 0) { - sk_X509_NAME_free(ca_list); - return nullptr; - } - - return ca_list; - } - - // SSL HTTP client implementation - inline SSLClient::SSLClient(const std::string& host) - : SSLClient(host, 443, std::string(), std::string()) {} - - inline SSLClient::SSLClient(const std::string& host, int port) - : SSLClient(host, port, std::string(), std::string()) {} - - inline SSLClient::SSLClient(const std::string& host, int port, - const std::string& client_cert_path, - const std::string& client_key_path, - const std::string& private_key_password) - : ClientImpl(host, port, client_cert_path, client_key_path) { - ctx_ = SSL_CTX_new(TLS_client_method()); - - SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION); - - detail::split(&host_[0], &host_[host_.size()], '.', - [&](const char* b, const char* e) { host_components_.emplace_back(b, e); }); - - if (!client_cert_path.empty() && !client_key_path.empty()) { - if (!private_key_password.empty()) { - SSL_CTX_set_default_passwd_cb_userdata( - ctx_, reinterpret_cast(const_cast(private_key_password.c_str()))); - } - - if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(), SSL_FILETYPE_PEM) != - 1 || - SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(), SSL_FILETYPE_PEM) != 1) { - last_openssl_error_ = ERR_get_error(); - SSL_CTX_free(ctx_); - ctx_ = nullptr; - } - } - } - - inline SSLClient::SSLClient(const std::string& host, int port, X509* client_cert, - EVP_PKEY* client_key, const std::string& private_key_password) - : ClientImpl(host, port) { - ctx_ = SSL_CTX_new(TLS_client_method()); - - detail::split(&host_[0], &host_[host_.size()], '.', - [&](const char* b, const char* e) { host_components_.emplace_back(b, e); }); - - if (client_cert != nullptr && client_key != nullptr) { - if (!private_key_password.empty()) { - SSL_CTX_set_default_passwd_cb_userdata( - ctx_, reinterpret_cast(const_cast(private_key_password.c_str()))); - } - - if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 || - SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) { - last_openssl_error_ = ERR_get_error(); - SSL_CTX_free(ctx_); - ctx_ = nullptr; - } - } - } - - inline SSLClient::~SSLClient() { - if (ctx_) { - SSL_CTX_free(ctx_); - } - // Make sure to shut down SSL since shutdown_ssl will resolve to the - // base function rather than the derived function once we get to the - // base class destructor, and won't free the SSL (causing a leak). - shutdown_ssl_impl(socket_, true); - } - - inline bool SSLClient::is_valid() const { return ctx_; } - - inline void SSLClient::set_ca_cert_store(X509_STORE* ca_cert_store) { - if (ca_cert_store) { - if (ctx_) { - if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) { - // Free memory allocated for old cert and use new store - // `ca_cert_store` - SSL_CTX_set_cert_store(ctx_, ca_cert_store); - ca_cert_store_ = ca_cert_store; - } - } else { - X509_STORE_free(ca_cert_store); - } - } - } - - inline void SSLClient::load_ca_cert_store(const char* ca_cert, std::size_t size) { - set_ca_cert_store(ClientImpl::create_ca_cert_store(ca_cert, size)); - } - - inline long SSLClient::get_openssl_verify_result() const { return verify_result_; } - - inline SSL_CTX* SSLClient::ssl_context() const { return ctx_; } - - inline bool SSLClient::create_and_connect_socket(Socket& socket, Error& error) { - if (!is_valid()) { - error = Error::SSLConnection; - return false; - } - return ClientImpl::create_and_connect_socket(socket, error); - } - - // Assumes that socket_mutex_ is locked and that there are no requests in - // flight - inline bool SSLClient::connect_with_proxy( - Socket& socket, std::chrono::time_point start_time, - Response& res, bool& success, Error& error) { - success = true; - Response proxy_res; - if (!detail::process_client_socket( - socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, - write_timeout_usec_, max_timeout_msec_, start_time, [&](Stream& strm) { - Request req2; - req2.method = "CONNECT"; - req2.path = host_and_port_; - if (max_timeout_msec_ > 0) { - req2.start_time_ = std::chrono::steady_clock::now(); - } - return process_request(strm, req2, proxy_res, false, error); - })) { - // Thread-safe to close everything because we are assuming there are no - // requests in flight - shutdown_ssl(socket, true); - shutdown_socket(socket); - close_socket(socket); - success = false; - return false; - } - - if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) { - if (!proxy_digest_auth_username_.empty() && !proxy_digest_auth_password_.empty()) { - std::map auth; - if (detail::parse_www_authenticate(proxy_res, auth, true)) { - // Close the current socket and create a new one for the authenticated - // request - shutdown_ssl(socket, true); - shutdown_socket(socket); - close_socket(socket); - - // Create a new socket for the authenticated CONNECT request - if (!create_and_connect_socket(socket, error)) { - success = false; - output_error_log(error, nullptr); - return false; - } - - proxy_res = Response(); - if (!detail::process_client_socket( - socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, - write_timeout_usec_, max_timeout_msec_, start_time, [&](Stream& strm) { - Request req3; - req3.method = "CONNECT"; - req3.path = host_and_port_; - req3.headers.insert(detail::make_digest_authentication_header( - req3, auth, 1, detail::random_string(10), - proxy_digest_auth_username_, proxy_digest_auth_password_, - true)); - if (max_timeout_msec_ > 0) { - req3.start_time_ = std::chrono::steady_clock::now(); - } - return process_request(strm, req3, proxy_res, false, error); - })) { - // Thread-safe to close everything because we are assuming there are - // no requests in flight - shutdown_ssl(socket, true); - shutdown_socket(socket); - close_socket(socket); - success = false; - return false; - } - } - } - } - - // If status code is not 200, proxy request is failed. - // Set error to ProxyConnection and return proxy response - // as the response of the request - if (proxy_res.status != StatusCode::OK_200) { - error = Error::ProxyConnection; - output_error_log(error, nullptr); - res = std::move(proxy_res); - // Thread-safe to close everything because we are assuming there are - // no requests in flight - shutdown_ssl(socket, true); - shutdown_socket(socket); - close_socket(socket); - return false; - } - - return true; - } - - inline bool SSLClient::load_certs() { - auto ret = true; - - std::call_once(initialize_cert_, [&]() { - std::lock_guard guard(ctx_mutex_); - if (!ca_cert_file_path_.empty()) { - if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(), nullptr)) { - last_openssl_error_ = ERR_get_error(); - ret = false; - } - } else if (!ca_cert_dir_path_.empty()) { - if (!SSL_CTX_load_verify_locations(ctx_, nullptr, ca_cert_dir_path_.c_str())) { - last_openssl_error_ = ERR_get_error(); - ret = false; - } - } else { - auto loaded = false; -#ifdef _WIN32 - loaded = detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_)); -#elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && TARGET_OS_MAC - loaded = detail::load_system_certs_on_macos(SSL_CTX_get_cert_store(ctx_)); -#endif // _WIN32 - if (!loaded) { - SSL_CTX_set_default_verify_paths(ctx_); - } - } - }); - - return ret; - } - - inline bool SSLClient::initialize_ssl(Socket& socket, Error& error) { - auto ssl = detail::ssl_new( - socket.sock, ctx_, ctx_mutex_, - [&](SSL* ssl2) { - if (server_certificate_verification_) { - if (!load_certs()) { - error = Error::SSLLoadingCerts; - output_error_log(error, nullptr); - return false; - } - SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr); - } - - if (!detail::ssl_connect_or_accept_nonblocking( - socket.sock, ssl2, SSL_connect, connection_timeout_sec_, - connection_timeout_usec_, &last_ssl_error_)) { - error = Error::SSLConnection; - output_error_log(error, nullptr); - return false; - } - - if (server_certificate_verification_) { - auto verification_status = SSLVerifierResponse::NoDecisionMade; - - if (server_certificate_verifier_) { - verification_status = server_certificate_verifier_(ssl2); - } - - if (verification_status == SSLVerifierResponse::CertificateRejected) { - last_openssl_error_ = ERR_get_error(); - error = Error::SSLServerVerification; - output_error_log(error, nullptr); - return false; - } - - if (verification_status == SSLVerifierResponse::NoDecisionMade) { - verify_result_ = SSL_get_verify_result(ssl2); - - if (verify_result_ != X509_V_OK) { - last_openssl_error_ = static_cast(verify_result_); - error = Error::SSLServerVerification; - output_error_log(error, nullptr); - return false; - } - - auto server_cert = SSL_get1_peer_certificate(ssl2); - auto se = detail::scope_exit([&] { X509_free(server_cert); }); - - if (server_cert == nullptr) { - last_openssl_error_ = ERR_get_error(); - error = Error::SSLServerVerification; - output_error_log(error, nullptr); - return false; - } - - if (server_hostname_verification_) { - if (!verify_host(server_cert)) { - last_openssl_error_ = X509_V_ERR_HOSTNAME_MISMATCH; - error = Error::SSLServerHostnameVerification; - output_error_log(error, nullptr); - return false; - } - } - } - } - - return true; - }, - [&](SSL* ssl2) { - // Set SNI only if host is not IP address - if (!detail::is_ip_address(host_)) { -#if defined(OPENSSL_IS_BORINGSSL) - SSL_set_tlsext_host_name(ssl2, host_.c_str()); -#else - // NOTE: Direct call instead of using the OpenSSL macro to suppress - // -Wold-style-cast warning - SSL_ctrl(ssl2, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, - static_cast(const_cast(host_.c_str()))); -#endif - } - return true; - }); - - if (ssl) { - socket.ssl = ssl; - return true; - } - - if (ctx_ == nullptr) { - error = Error::SSLConnection; - last_openssl_error_ = ERR_get_error(); - } - - shutdown_socket(socket); - close_socket(socket); - return false; - } - - inline void SSLClient::shutdown_ssl(Socket& socket, bool shutdown_gracefully) { - shutdown_ssl_impl(socket, shutdown_gracefully); - } - - inline void SSLClient::shutdown_ssl_impl(Socket& socket, bool shutdown_gracefully) { - if (socket.sock == INVALID_SOCKET) { - assert(socket.ssl == nullptr); - return; - } - if (socket.ssl) { - detail::ssl_delete(ctx_mutex_, socket.ssl, socket.sock, shutdown_gracefully); - socket.ssl = nullptr; - } - assert(socket.ssl == nullptr); - } - - inline bool SSLClient::process_socket( - const Socket& socket, std::chrono::time_point start_time, - std::function callback) { - assert(socket.ssl); - return detail::process_client_socket_ssl( - socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, - write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback)); - } - - inline bool SSLClient::is_ssl() const { return true; } - - inline bool SSLClient::verify_host(X509* server_cert) const { - /* Quote from RFC2818 section 3.1 "Server Identity" - - If a subjectAltName extension of type dNSName is present, that MUST - be used as the identity. Otherwise, the (most specific) Common Name - field in the Subject field of the certificate MUST be used. Although - the use of the Common Name is existing practice, it is deprecated and - Certification Authorities are encouraged to use the dNSName instead. - - Matching is performed using the matching rules specified by - [RFC2459]. If more than one identity of a given type is present in - the certificate (e.g., more than one dNSName name, a match in any one - of the set is considered acceptable.) Names may contain the wildcard - character * which is considered to match any single domain name - component or component fragment. E.g., *.a.com matches foo.a.com but - not bar.foo.a.com. f*.com matches foo.com but not bar.com. - - In some cases, the URI is specified as an IP address rather than a - hostname. In this case, the iPAddress subjectAltName must be present - in the certificate and must exactly match the IP in the URI. - - */ - return verify_host_with_subject_alt_name(server_cert) || - verify_host_with_common_name(server_cert); - } - - inline bool SSLClient::verify_host_with_subject_alt_name(X509* server_cert) const { - auto ret = false; - - auto type = GEN_DNS; - - struct in6_addr addr6 = {}; - struct in_addr addr = {}; - size_t addr_len = 0; - -#ifndef __MINGW32__ - if (inet_pton(AF_INET6, host_.c_str(), &addr6)) { - type = GEN_IPADD; - addr_len = sizeof(struct in6_addr); - } else if (inet_pton(AF_INET, host_.c_str(), &addr)) { - type = GEN_IPADD; - addr_len = sizeof(struct in_addr); - } -#endif - - auto alt_names = static_cast( - X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr)); - - if (alt_names) { - auto dsn_matched = false; - auto ip_matched = false; - - auto count = sk_GENERAL_NAME_num(alt_names); - - for (decltype(count) i = 0; i < count && !dsn_matched; i++) { - auto val = sk_GENERAL_NAME_value(alt_names, i); - if (!val || val->type != type) { - continue; - } - - auto name = reinterpret_cast(ASN1_STRING_get0_data(val->d.ia5)); - if (name == nullptr) { - continue; - } - - auto name_len = static_cast(ASN1_STRING_length(val->d.ia5)); - - switch (type) { - case GEN_DNS: - dsn_matched = check_host_name(name, name_len); - break; - - case GEN_IPADD: - if (!memcmp(&addr6, name, addr_len) || !memcmp(&addr, name, addr_len)) { - ip_matched = true; - } - break; - } - } - - if (dsn_matched || ip_matched) { - ret = true; - } - } - - GENERAL_NAMES_free(const_cast( - reinterpret_cast(alt_names))); - return ret; - } - - inline bool SSLClient::verify_host_with_common_name(X509* server_cert) const { - const auto subject_name = X509_get_subject_name(server_cert); - - if (subject_name != nullptr) { - char name[BUFSIZ]; - auto name_len = - X509_NAME_get_text_by_NID(subject_name, NID_commonName, name, sizeof(name)); - - if (name_len != -1) { - return check_host_name(name, static_cast(name_len)); - } - } - - return false; - } - - inline bool SSLClient::check_host_name(const char* pattern, size_t pattern_len) const { - if (host_.size() == pattern_len && host_ == pattern) { - return true; - } - - // Wildcard match - // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484 - std::vector pattern_components; - detail::split(&pattern[0], &pattern[pattern_len], '.', - [&](const char* b, const char* e) { pattern_components.emplace_back(b, e); }); - - if (host_components_.size() != pattern_components.size()) { - return false; - } - - auto itr = pattern_components.begin(); - for (const auto& h : host_components_) { - auto& p = *itr; - if (p != h && p != "*") { - auto partial_match = - (p.size() > 0 && p[p.size() - 1] == '*' && !p.compare(0, p.size() - 1, h)); - if (!partial_match) { - return false; - } - } - ++itr; - } - - return true; - } -#endif - - // Universal client implementation - inline Client::Client(const std::string& scheme_host_port) - : Client(scheme_host_port, std::string(), std::string()) {} - - inline Client::Client(const std::string& scheme_host_port, const std::string& client_cert_path, - const std::string& client_key_path) { - const static std::regex re( - R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)"); - - std::smatch m; - if (std::regex_match(scheme_host_port, m, re)) { - auto scheme = m[1].str(); - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - if (!scheme.empty() && (scheme != "http" && scheme != "https")) { -#else - if (!scheme.empty() && scheme != "http") { -#endif -#ifndef CPPHTTPLIB_NO_EXCEPTIONS - std::string msg = "'" + scheme + "' scheme is not supported."; - throw std::invalid_argument(msg); -#endif - return; - } - - auto is_ssl = scheme == "https"; - - auto host = m[2].str(); - if (host.empty()) { - host = m[3].str(); - } - - auto port_str = m[4].str(); - auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80); - - if (is_ssl) { -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - cli_ = - detail::make_unique(host, port, client_cert_path, client_key_path); - is_ssl_ = is_ssl; -#endif - } else { - cli_ = - detail::make_unique(host, port, client_cert_path, client_key_path); - } - } else { - // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress) - // if port param below changes. - cli_ = detail::make_unique(scheme_host_port, 80, client_cert_path, - client_key_path); - } - } // namespace detail - - inline Client::Client(const std::string& host, int port) - : cli_(detail::make_unique(host, port)) {} - - inline Client::Client(const std::string& host, int port, const std::string& client_cert_path, - const std::string& client_key_path) - : cli_(detail::make_unique(host, port, client_cert_path, client_key_path)) {} - - inline Client::~Client() = default; - - inline bool Client::is_valid() const { return cli_ != nullptr && cli_->is_valid(); } - - inline Result Client::Get(const std::string& path, DownloadProgress progress) { - return cli_->Get(path, std::move(progress)); - } - inline Result Client::Get(const std::string& path, const Headers& headers, - DownloadProgress progress) { - return cli_->Get(path, headers, std::move(progress)); - } - inline Result Client::Get(const std::string& path, ContentReceiver content_receiver, - DownloadProgress progress) { - return cli_->Get(path, std::move(content_receiver), std::move(progress)); - } - inline Result Client::Get(const std::string& path, const Headers& headers, - ContentReceiver content_receiver, DownloadProgress progress) { - return cli_->Get(path, headers, std::move(content_receiver), std::move(progress)); - } - inline Result Client::Get(const std::string& path, ResponseHandler response_handler, - ContentReceiver content_receiver, DownloadProgress progress) { - return cli_->Get(path, std::move(response_handler), std::move(content_receiver), - std::move(progress)); - } - inline Result Client::Get(const std::string& path, const Headers& headers, - ResponseHandler response_handler, ContentReceiver content_receiver, - DownloadProgress progress) { - return cli_->Get(path, headers, std::move(response_handler), std::move(content_receiver), - std::move(progress)); - } - inline Result Client::Get(const std::string& path, const Params& params, const Headers& headers, - DownloadProgress progress) { - return cli_->Get(path, params, headers, std::move(progress)); - } - inline Result Client::Get(const std::string& path, const Params& params, const Headers& headers, - ContentReceiver content_receiver, DownloadProgress progress) { - return cli_->Get(path, params, headers, std::move(content_receiver), std::move(progress)); - } - inline Result Client::Get(const std::string& path, const Params& params, const Headers& headers, - ResponseHandler response_handler, ContentReceiver content_receiver, - DownloadProgress progress) { - return cli_->Get(path, params, headers, std::move(response_handler), - std::move(content_receiver), std::move(progress)); - } - - inline Result Client::Head(const std::string& path) { return cli_->Head(path); } - inline Result Client::Head(const std::string& path, const Headers& headers) { - return cli_->Head(path, headers); - } - - inline Result Client::Post(const std::string& path) { return cli_->Post(path); } - inline Result Client::Post(const std::string& path, const Headers& headers) { - return cli_->Post(path, headers); - } - inline Result Client::Post(const std::string& path, const char* body, size_t content_length, - const std::string& content_type, UploadProgress progress) { - return cli_->Post(path, body, content_length, content_type, progress); - } - inline Result Client::Post(const std::string& path, const Headers& headers, const char* body, - size_t content_length, const std::string& content_type, - UploadProgress progress) { - return cli_->Post(path, headers, body, content_length, content_type, progress); - } - inline Result Client::Post(const std::string& path, const std::string& body, - const std::string& content_type, UploadProgress progress) { - return cli_->Post(path, body, content_type, progress); - } - inline Result Client::Post(const std::string& path, const Headers& headers, - const std::string& body, const std::string& content_type, - UploadProgress progress) { - return cli_->Post(path, headers, body, content_type, progress); - } - inline Result Client::Post(const std::string& path, size_t content_length, - ContentProvider content_provider, const std::string& content_type, - UploadProgress progress) { - return cli_->Post(path, content_length, std::move(content_provider), content_type, - progress); - } - inline Result Client::Post(const std::string& path, size_t content_length, - ContentProvider content_provider, const std::string& content_type, - ContentReceiver content_receiver, UploadProgress progress) { - return cli_->Post(path, content_length, std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - inline Result Client::Post(const std::string& path, - ContentProviderWithoutLength content_provider, - const std::string& content_type, UploadProgress progress) { - return cli_->Post(path, std::move(content_provider), content_type, progress); - } - inline Result Client::Post(const std::string& path, - ContentProviderWithoutLength content_provider, - const std::string& content_type, ContentReceiver content_receiver, - UploadProgress progress) { - return cli_->Post(path, std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - inline Result Client::Post(const std::string& path, const Headers& headers, - size_t content_length, ContentProvider content_provider, - const std::string& content_type, UploadProgress progress) { - return cli_->Post(path, headers, content_length, std::move(content_provider), content_type, - progress); - } - inline Result Client::Post(const std::string& path, const Headers& headers, - size_t content_length, ContentProvider content_provider, - const std::string& content_type, ContentReceiver content_receiver, - DownloadProgress progress) { - return cli_->Post(path, headers, content_length, std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - inline Result Client::Post(const std::string& path, const Headers& headers, - ContentProviderWithoutLength content_provider, - const std::string& content_type, UploadProgress progress) { - return cli_->Post(path, headers, std::move(content_provider), content_type, progress); - } - inline Result Client::Post(const std::string& path, const Headers& headers, - ContentProviderWithoutLength content_provider, - const std::string& content_type, ContentReceiver content_receiver, - DownloadProgress progress) { - return cli_->Post(path, headers, std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - inline Result Client::Post(const std::string& path, const Params& params) { - return cli_->Post(path, params); - } - inline Result Client::Post(const std::string& path, const Headers& headers, - const Params& params) { - return cli_->Post(path, headers, params); - } - inline Result Client::Post(const std::string& path, const UploadFormDataItems& items, - UploadProgress progress) { - return cli_->Post(path, items, progress); - } - inline Result Client::Post(const std::string& path, const Headers& headers, - const UploadFormDataItems& items, UploadProgress progress) { - return cli_->Post(path, headers, items, progress); - } - inline Result Client::Post(const std::string& path, const Headers& headers, - const UploadFormDataItems& items, const std::string& boundary, - UploadProgress progress) { - return cli_->Post(path, headers, items, boundary, progress); - } - inline Result Client::Post(const std::string& path, const Headers& headers, - const UploadFormDataItems& items, - const FormDataProviderItems& provider_items, - UploadProgress progress) { - return cli_->Post(path, headers, items, provider_items, progress); - } - inline Result Client::Post(const std::string& path, const Headers& headers, - const std::string& body, const std::string& content_type, - ContentReceiver content_receiver, DownloadProgress progress) { - return cli_->Post(path, headers, body, content_type, std::move(content_receiver), progress); - } - - inline Result Client::Put(const std::string& path) { return cli_->Put(path); } - inline Result Client::Put(const std::string& path, const Headers& headers) { - return cli_->Put(path, headers); - } - inline Result Client::Put(const std::string& path, const char* body, size_t content_length, - const std::string& content_type, UploadProgress progress) { - return cli_->Put(path, body, content_length, content_type, progress); - } - inline Result Client::Put(const std::string& path, const Headers& headers, const char* body, - size_t content_length, const std::string& content_type, - UploadProgress progress) { - return cli_->Put(path, headers, body, content_length, content_type, progress); - } - inline Result Client::Put(const std::string& path, const std::string& body, - const std::string& content_type, UploadProgress progress) { - return cli_->Put(path, body, content_type, progress); - } - inline Result Client::Put(const std::string& path, const Headers& headers, - const std::string& body, const std::string& content_type, - UploadProgress progress) { - return cli_->Put(path, headers, body, content_type, progress); - } - inline Result Client::Put(const std::string& path, size_t content_length, - ContentProvider content_provider, const std::string& content_type, - UploadProgress progress) { - return cli_->Put(path, content_length, std::move(content_provider), content_type, progress); - } - inline Result Client::Put(const std::string& path, size_t content_length, - ContentProvider content_provider, const std::string& content_type, - ContentReceiver content_receiver, UploadProgress progress) { - return cli_->Put(path, content_length, std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - inline Result Client::Put(const std::string& path, - ContentProviderWithoutLength content_provider, - const std::string& content_type, UploadProgress progress) { - return cli_->Put(path, std::move(content_provider), content_type, progress); - } - inline Result Client::Put(const std::string& path, - ContentProviderWithoutLength content_provider, - const std::string& content_type, ContentReceiver content_receiver, - UploadProgress progress) { - return cli_->Put(path, std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - inline Result Client::Put(const std::string& path, const Headers& headers, - size_t content_length, ContentProvider content_provider, - const std::string& content_type, UploadProgress progress) { - return cli_->Put(path, headers, content_length, std::move(content_provider), content_type, - progress); - } - inline Result Client::Put(const std::string& path, const Headers& headers, - size_t content_length, ContentProvider content_provider, - const std::string& content_type, ContentReceiver content_receiver, - UploadProgress progress) { - return cli_->Put(path, headers, content_length, std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - inline Result Client::Put(const std::string& path, const Headers& headers, - ContentProviderWithoutLength content_provider, - const std::string& content_type, UploadProgress progress) { - return cli_->Put(path, headers, std::move(content_provider), content_type, progress); - } - inline Result Client::Put(const std::string& path, const Headers& headers, - ContentProviderWithoutLength content_provider, - const std::string& content_type, ContentReceiver content_receiver, - UploadProgress progress) { - return cli_->Put(path, headers, std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - inline Result Client::Put(const std::string& path, const Params& params) { - return cli_->Put(path, params); - } - inline Result Client::Put(const std::string& path, const Headers& headers, - const Params& params) { - return cli_->Put(path, headers, params); - } - inline Result Client::Put(const std::string& path, const UploadFormDataItems& items, - UploadProgress progress) { - return cli_->Put(path, items, progress); - } - inline Result Client::Put(const std::string& path, const Headers& headers, - const UploadFormDataItems& items, UploadProgress progress) { - return cli_->Put(path, headers, items, progress); - } - inline Result Client::Put(const std::string& path, const Headers& headers, - const UploadFormDataItems& items, const std::string& boundary, - UploadProgress progress) { - return cli_->Put(path, headers, items, boundary, progress); - } - inline Result Client::Put(const std::string& path, const Headers& headers, - const UploadFormDataItems& items, - const FormDataProviderItems& provider_items, - UploadProgress progress) { - return cli_->Put(path, headers, items, provider_items, progress); - } - inline Result Client::Put(const std::string& path, const Headers& headers, - const std::string& body, const std::string& content_type, - ContentReceiver content_receiver, DownloadProgress progress) { - return cli_->Put(path, headers, body, content_type, content_receiver, progress); - } - - inline Result Client::Patch(const std::string& path) { return cli_->Patch(path); } - inline Result Client::Patch(const std::string& path, const Headers& headers) { - return cli_->Patch(path, headers); - } - inline Result Client::Patch(const std::string& path, const char* body, size_t content_length, - const std::string& content_type, UploadProgress progress) { - return cli_->Patch(path, body, content_length, content_type, progress); - } - inline Result Client::Patch(const std::string& path, const Headers& headers, const char* body, - size_t content_length, const std::string& content_type, - UploadProgress progress) { - return cli_->Patch(path, headers, body, content_length, content_type, progress); - } - inline Result Client::Patch(const std::string& path, const std::string& body, - const std::string& content_type, UploadProgress progress) { - return cli_->Patch(path, body, content_type, progress); - } - inline Result Client::Patch(const std::string& path, const Headers& headers, - const std::string& body, const std::string& content_type, - UploadProgress progress) { - return cli_->Patch(path, headers, body, content_type, progress); - } - inline Result Client::Patch(const std::string& path, size_t content_length, - ContentProvider content_provider, const std::string& content_type, - UploadProgress progress) { - return cli_->Patch(path, content_length, std::move(content_provider), content_type, - progress); - } - inline Result Client::Patch(const std::string& path, size_t content_length, - ContentProvider content_provider, const std::string& content_type, - ContentReceiver content_receiver, UploadProgress progress) { - return cli_->Patch(path, content_length, std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - inline Result Client::Patch(const std::string& path, - ContentProviderWithoutLength content_provider, - const std::string& content_type, UploadProgress progress) { - return cli_->Patch(path, std::move(content_provider), content_type, progress); - } - inline Result Client::Patch(const std::string& path, - ContentProviderWithoutLength content_provider, - const std::string& content_type, ContentReceiver content_receiver, - UploadProgress progress) { - return cli_->Patch(path, std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - inline Result Client::Patch(const std::string& path, const Headers& headers, - size_t content_length, ContentProvider content_provider, - const std::string& content_type, UploadProgress progress) { - return cli_->Patch(path, headers, content_length, std::move(content_provider), content_type, - progress); - } - inline Result Client::Patch(const std::string& path, const Headers& headers, - size_t content_length, ContentProvider content_provider, - const std::string& content_type, ContentReceiver content_receiver, - UploadProgress progress) { - return cli_->Patch(path, headers, content_length, std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - inline Result Client::Patch(const std::string& path, const Headers& headers, - ContentProviderWithoutLength content_provider, - const std::string& content_type, UploadProgress progress) { - return cli_->Patch(path, headers, std::move(content_provider), content_type, progress); - } - inline Result Client::Patch(const std::string& path, const Headers& headers, - ContentProviderWithoutLength content_provider, - const std::string& content_type, ContentReceiver content_receiver, - UploadProgress progress) { - return cli_->Patch(path, headers, std::move(content_provider), content_type, - std::move(content_receiver), progress); - } - inline Result Client::Patch(const std::string& path, const Params& params) { - return cli_->Patch(path, params); - } - inline Result Client::Patch(const std::string& path, const Headers& headers, - const Params& params) { - return cli_->Patch(path, headers, params); - } - inline Result Client::Patch(const std::string& path, const UploadFormDataItems& items, - UploadProgress progress) { - return cli_->Patch(path, items, progress); - } - inline Result Client::Patch(const std::string& path, const Headers& headers, - const UploadFormDataItems& items, UploadProgress progress) { - return cli_->Patch(path, headers, items, progress); - } - inline Result Client::Patch(const std::string& path, const Headers& headers, - const UploadFormDataItems& items, const std::string& boundary, - UploadProgress progress) { - return cli_->Patch(path, headers, items, boundary, progress); - } - inline Result Client::Patch(const std::string& path, const Headers& headers, - const UploadFormDataItems& items, - const FormDataProviderItems& provider_items, - UploadProgress progress) { - return cli_->Patch(path, headers, items, provider_items, progress); - } - inline Result Client::Patch(const std::string& path, const Headers& headers, - const std::string& body, const std::string& content_type, - ContentReceiver content_receiver, DownloadProgress progress) { - return cli_->Patch(path, headers, body, content_type, content_receiver, progress); - } - - inline Result Client::Delete(const std::string& path, DownloadProgress progress) { - return cli_->Delete(path, progress); - } - inline Result Client::Delete(const std::string& path, const Headers& headers, - DownloadProgress progress) { - return cli_->Delete(path, headers, progress); - } - inline Result Client::Delete(const std::string& path, const char* body, size_t content_length, - const std::string& content_type, DownloadProgress progress) { - return cli_->Delete(path, body, content_length, content_type, progress); - } - inline Result Client::Delete(const std::string& path, const Headers& headers, const char* body, - size_t content_length, const std::string& content_type, - DownloadProgress progress) { - return cli_->Delete(path, headers, body, content_length, content_type, progress); - } - inline Result Client::Delete(const std::string& path, const std::string& body, - const std::string& content_type, DownloadProgress progress) { - return cli_->Delete(path, body, content_type, progress); - } - inline Result Client::Delete(const std::string& path, const Headers& headers, - const std::string& body, const std::string& content_type, - DownloadProgress progress) { - return cli_->Delete(path, headers, body, content_type, progress); - } - inline Result Client::Delete(const std::string& path, const Params& params, - DownloadProgress progress) { - return cli_->Delete(path, params, progress); - } - inline Result Client::Delete(const std::string& path, const Headers& headers, - const Params& params, DownloadProgress progress) { - return cli_->Delete(path, headers, params, progress); - } - - inline Result Client::Options(const std::string& path) { return cli_->Options(path); } - inline Result Client::Options(const std::string& path, const Headers& headers) { - return cli_->Options(path, headers); - } - - inline bool Client::send(Request& req, Response& res, Error& error) { - return cli_->send(req, res, error); - } - - inline Result Client::send(const Request& req) { return cli_->send(req); } - - inline void Client::stop() { cli_->stop(); } - - inline std::string Client::host() const { return cli_->host(); } - - inline int Client::port() const { return cli_->port(); } - - inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); } - - inline socket_t Client::socket() const { return cli_->socket(); } - - inline void Client::set_hostname_addr_map(std::map addr_map) { - cli_->set_hostname_addr_map(std::move(addr_map)); - } - - inline void Client::set_default_headers(Headers headers) { - cli_->set_default_headers(std::move(headers)); - } - - inline void Client::set_header_writer(std::function const& writer) { - cli_->set_header_writer(writer); - } - - inline void Client::set_address_family(int family) { cli_->set_address_family(family); } - - inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); } - - inline void Client::set_socket_options(SocketOptions socket_options) { - cli_->set_socket_options(std::move(socket_options)); - } - - inline void Client::set_connection_timeout(time_t sec, time_t usec) { - cli_->set_connection_timeout(sec, usec); - } - - inline void Client::set_read_timeout(time_t sec, time_t usec) { - cli_->set_read_timeout(sec, usec); - } - - inline void Client::set_write_timeout(time_t sec, time_t usec) { - cli_->set_write_timeout(sec, usec); - } - - inline void Client::set_basic_auth(const std::string& username, const std::string& password) { - cli_->set_basic_auth(username, password); - } - inline void Client::set_bearer_token_auth(const std::string& token) { - cli_->set_bearer_token_auth(token); - } -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - inline void Client::set_digest_auth(const std::string& username, const std::string& password) { - cli_->set_digest_auth(username, password); - } -#endif - - inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); } - inline void Client::set_follow_location(bool on) { cli_->set_follow_location(on); } - - inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); } - - [[deprecated("Use set_path_encode instead")]] inline void Client::set_url_encode(bool on) { - cli_->set_path_encode(on); - } - - inline void Client::set_compress(bool on) { cli_->set_compress(on); } - - inline void Client::set_decompress(bool on) { cli_->set_decompress(on); } - - inline void Client::set_interface(const std::string& intf) { cli_->set_interface(intf); } - - inline void Client::set_proxy(const std::string& host, int port) { - cli_->set_proxy(host, port); - } - inline void Client::set_proxy_basic_auth(const std::string& username, - const std::string& password) { - cli_->set_proxy_basic_auth(username, password); - } - inline void Client::set_proxy_bearer_token_auth(const std::string& token) { - cli_->set_proxy_bearer_token_auth(token); - } -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - inline void Client::set_proxy_digest_auth(const std::string& username, - const std::string& password) { - cli_->set_proxy_digest_auth(username, password); - } -#endif - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - inline void Client::enable_server_certificate_verification(bool enabled) { - cli_->enable_server_certificate_verification(enabled); - } - - inline void Client::enable_server_hostname_verification(bool enabled) { - cli_->enable_server_hostname_verification(enabled); - } - - inline void Client::set_server_certificate_verifier( - std::function verifier) { - cli_->set_server_certificate_verifier(verifier); - } -#endif - - inline void Client::set_logger(Logger logger) { cli_->set_logger(std::move(logger)); } - - inline void Client::set_error_logger(ErrorLogger error_logger) { - cli_->set_error_logger(std::move(error_logger)); - } - -#ifdef CPPHTTPLIB_OPENSSL_SUPPORT - inline void Client::set_ca_cert_path(const std::string& ca_cert_file_path, - const std::string& ca_cert_dir_path) { - cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path); - } - - inline void Client::set_ca_cert_store(X509_STORE* ca_cert_store) { - if (is_ssl_) { - static_cast(*cli_).set_ca_cert_store(ca_cert_store); - } else { - cli_->set_ca_cert_store(ca_cert_store); - } - } - - inline void Client::load_ca_cert_store(const char* ca_cert, std::size_t size) { - set_ca_cert_store(cli_->create_ca_cert_store(ca_cert, size)); - } - - inline long Client::get_openssl_verify_result() const { - if (is_ssl_) { - return static_cast(*cli_).get_openssl_verify_result(); - } - return -1; // NOTE: -1 doesn't match any of X509_V_ERR_??? - } - - inline SSL_CTX* Client::ssl_context() const { - if (is_ssl_) { - return static_cast(*cli_).ssl_context(); - } - return nullptr; - } -#endif - - // ---------------------------------------------------------------------------- - -} // namespace httplib - -#endif // CPPHTTPLIB_HTTPLIB_H diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index effb903..4660b4f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,22 +1,43 @@ -enable_testing() - -set(TEST_SOURCES +set( + BLOCH_TEST_SOURCES test_main.cpp - test_lexer.cpp test_ast.cpp + test_lexer.cpp test_parser.cpp test_semantics.cpp test_runtime.cpp ) -if (NOT WIN32) - list(APPEND TEST_SOURCES test_integration.cpp) +if(NOT WIN32) + list(APPEND BLOCH_TEST_SOURCES test_integration.cpp) endif() -add_executable(bloch_tests ${TEST_SOURCES}) +add_executable( + basis_tests + ${BLOCH_TEST_SOURCES} +) + +target_compile_features( + basis_tests + PRIVATE + cxx_std_20 +) + +target_link_libraries( + basis_tests + PRIVATE + bloch::runtime + bloch::project_warnings +) -target_link_libraries(bloch_tests - bloch_runtime +set_target_properties( + basis_tests + PROPERTIES + CXX_EXTENSIONS OFF + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin" ) -add_test(NAME bloch_tests COMMAND bloch_tests) +add_test( + NAME basis.tests + COMMAND basis_tests +) \ No newline at end of file diff --git a/tests/test_ast.cpp b/tests/test_ast.cpp index 2950108..bb8a0ff 100644 --- a/tests/test_ast.cpp +++ b/tests/test_ast.cpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/tests/test_framework.hpp b/tests/test_framework.hpp index 9ad8d6d..eb0bf08 100644 --- a/tests/test_framework.hpp +++ b/tests/test_framework.hpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,129 +22,125 @@ #include namespace test_framework { - struct TestCase { - std::string name; - std::function func; - }; - - inline std::vector& registry() { - static std::vector tests; - return tests; - } +struct TestCase { + std::string name; + std::function func; +}; + +inline std::vector& registry() { + static std::vector tests; + return tests; +} - inline void register_test(const std::string& name, std::function func) { - registry().push_back({name, std::move(func)}); - } +inline void register_test(const std::string& name, std::function func) { + registry().push_back({name, std::move(func)}); +} - inline int run_all() { - int failures = 0; - for (auto& t : registry()) { - try { - t.func(); - std::cout << "[PASS] " << t.name << "\n"; - } catch (const std::exception& e) { - std::cout << "[FAIL] " << t.name << ": " << e.what() << "\n"; - failures++; - } +inline int run_all() { + int failures = 0; + for (auto& t : registry()) { + try { + t.func(); + std::cout << "[PASS] " << t.name << "\n"; + } catch (const std::exception& e) { + std::cout << "[FAIL] " << t.name << ": " << e.what() << "\n"; + failures++; } - std::cout << registry().size() - failures << " tests passed, " << failures << " failed." - << std::endl; - return failures; } + std::cout << registry().size() - failures << " tests passed, " << failures << " failed." + << std::endl; + return failures; +} - inline std::string location(const char* file, int line) { +inline std::string location(const char* file, int line) { + std::ostringstream oss; + oss << file << ":" << line << " "; + return oss.str(); +} + +template +void expect_eq(const A& a, const B& b, const char* as, const char* bs, const char* file, int line) { + if (!(a == b)) { std::ostringstream oss; - oss << file << ":" << line << " "; - return oss.str(); + oss << location(file, line) << "Expected " << as << " == " << bs; + throw std::runtime_error(oss.str()); } +} - template - void expect_eq(const A& a, const B& b, const char* as, const char* bs, const char* file, - int line) { - if (!(a == b)) { - std::ostringstream oss; - oss << location(file, line) << "Expected " << as << " == " << bs; - throw std::runtime_error(oss.str()); - } +template +void expect_ne(const A& a, const B& b, const char* as, const char* bs, const char* file, int line) { + if (!(a != b)) { + std::ostringstream oss; + oss << location(file, line) << "Expected " << as << " != " << bs; + throw std::runtime_error(oss.str()); } +} - template - void expect_ne(const A& a, const B& b, const char* as, const char* bs, const char* file, - int line) { - if (!(a != b)) { - std::ostringstream oss; - oss << location(file, line) << "Expected " << as << " != " << bs; - throw std::runtime_error(oss.str()); - } +template +void expect_gt(const A& a, const B& b, const char* as, const char* bs, const char* file, int line) { + if (!(a > b)) { + std::ostringstream oss; + oss << location(file, line) << "Expected " << as << " > " << bs; + throw std::runtime_error(oss.str()); } +} - template - void expect_gt(const A& a, const B& b, const char* as, const char* bs, const char* file, - int line) { - if (!(a > b)) { - std::ostringstream oss; - oss << location(file, line) << "Expected " << as << " > " << bs; - throw std::runtime_error(oss.str()); - } +template +void expect_ge(const A& a, const B& b, const char* as, const char* bs, const char* file, int line) { + if (!(a >= b)) { + std::ostringstream oss; + oss << location(file, line) << "Expected " << as << " >= " << bs; + throw std::runtime_error(oss.str()); } +} - template - void expect_ge(const A& a, const B& b, const char* as, const char* bs, const char* file, - int line) { - if (!(a >= b)) { - std::ostringstream oss; - oss << location(file, line) << "Expected " << as << " >= " << bs; - throw std::runtime_error(oss.str()); - } +inline void expect_true(bool cond, const char* expr, const char* file, int line) { + if (!cond) { + std::ostringstream oss; + oss << location(file, line) << "Expected " << expr; + throw std::runtime_error(oss.str()); } +} - inline void expect_true(bool cond, const char* expr, const char* file, int line) { - if (!cond) { - std::ostringstream oss; - oss << location(file, line) << "Expected " << expr; - throw std::runtime_error(oss.str()); - } +inline void expect_false(bool cond, const char* expr, const char* file, int line) { + if (cond) { + std::ostringstream oss; + oss << location(file, line) << "Expected !(" << expr << ")"; + throw std::runtime_error(oss.str()); } +} - inline void expect_false(bool cond, const char* expr, const char* file, int line) { - if (cond) { - std::ostringstream oss; - oss << location(file, line) << "Expected !(" << expr << ")"; - throw std::runtime_error(oss.str()); - } +inline void expect_no_throw(const std::function& fn, const char* expr, const char* file, + int line) { + try { + fn(); + } catch (const std::exception& e) { + std::ostringstream oss; + oss << location(file, line) << "Unexpected exception in " << expr << ": " << e.what(); + throw std::runtime_error(oss.str()); + } catch (...) { + std::ostringstream oss; + oss << location(file, line) << "Unexpected non-std exception in " << expr; + throw std::runtime_error(oss.str()); } +} - inline void expect_no_throw(const std::function& fn, const char* expr, const char* file, - int line) { - try { - fn(); - } catch (const std::exception& e) { - std::ostringstream oss; - oss << location(file, line) << "Unexpected exception in " << expr << ": " << e.what(); - throw std::runtime_error(oss.str()); - } catch (...) { - std::ostringstream oss; - oss << location(file, line) << "Unexpected non-std exception in " << expr; - throw std::runtime_error(oss.str()); - } +template +inline void expect_throw(F&& fn, const char* expr, const char* file, int line) { + bool caught = false; + try { + fn(); + } catch (const E&) { + caught = true; + } catch (...) { } - - template - inline void expect_throw(F&& fn, const char* expr, const char* file, int line) { - bool caught = false; - try { - fn(); - } catch (const E&) { - caught = true; - } catch (...) { - } - if (!caught) { - std::ostringstream oss; - oss << location(file, line) << "Expected " << expr << " to throw " << typeid(E).name(); - throw std::runtime_error(oss.str()); - } + if (!caught) { + std::ostringstream oss; + oss << location(file, line) << "Expected " << expr << " to throw " << typeid(E).name(); + throw std::runtime_error(oss.str()); } } +} // namespace test_framework #define TEST(suite, name) \ static void suite##_##name(); \ diff --git a/tests/test_integration.cpp b/tests/test_integration.cpp index 8fdf176..3ea9bf8 100644 --- a/tests/test_integration.cpp +++ b/tests/test_integration.cpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -35,162 +35,160 @@ TEST(IntegrationTest, SkippedOnWindows) { EXPECT_TRUE(true); } #include "test_framework.hpp" namespace { - // Determine directory of the currently running test executable - std::filesystem::path executableDir() { +// Determine directory of the currently running test executable +std::filesystem::path executableDir() { #if defined(_WIN32) - char buf[MAX_PATH]; - DWORD len = GetModuleFileNameA(nullptr, buf, MAX_PATH); - if (len > 0) { - std::filesystem::path p(buf); - return p.parent_path(); - } - return std::filesystem::current_path(); + char buf[MAX_PATH]; + DWORD len = GetModuleFileNameA(nullptr, buf, MAX_PATH); + if (len > 0) { + std::filesystem::path p(buf); + return p.parent_path(); + } + return std::filesystem::current_path(); #elif defined(__APPLE__) - uint32_t size = 0; - _NSGetExecutablePath(nullptr, &size); - std::string path; - path.resize(size + 1); - if (_NSGetExecutablePath(path.data(), &size) == 0) { - std::filesystem::path p(path.c_str()); - return p.parent_path(); - } - return std::filesystem::current_path(); + uint32_t size = 0; + _NSGetExecutablePath(nullptr, &size); + std::string path; + path.resize(size + 1); + if (_NSGetExecutablePath(path.data(), &size) == 0) { + std::filesystem::path p(path.c_str()); + return p.parent_path(); + } + return std::filesystem::current_path(); #else - char buf[4096]; - ssize_t len = readlink("/proc/self/exe", buf, sizeof(buf) - 1); - if (len > 0) { - buf[len] = '\0'; - std::filesystem::path p(buf); - return p.parent_path(); - } - return std::filesystem::current_path(); -#endif + char buf[4096]; + ssize_t len = readlink("/proc/self/exe", buf, sizeof(buf) - 1); + if (len > 0) { + buf[len] = '\0'; + std::filesystem::path p(buf); + return p.parent_path(); } + return std::filesystem::current_path(); +#endif +} - std::filesystem::path findBlochBinary() { - namespace fs = std::filesystem; - fs::path base = executableDir(); +std::filesystem::path findBlochBinary() { + namespace fs = std::filesystem; + fs::path base = executableDir(); #if defined(_WIN32) - const char* exe = "bloch.exe"; + const char* exe = "basis.exe"; #else - const char* exe = "bloch"; + const char* exe = "basis"; #endif - std::vector candidates = { - base / exe, - base.parent_path() / exe, - base / ".." / exe, - fs::current_path() / "bin" / exe, - fs::current_path() / "bin" / "Release" / exe, - fs::current_path().parent_path() / "bin" / exe, - fs::current_path().parent_path() / "bin" / "Release" / exe, - }; - for (auto& p : candidates) { - std::error_code ec; - if (fs::exists(p, ec)) - return fs::weakly_canonical(p, ec); - } - return exe; + std::vector candidates = { + base / exe, + base.parent_path() / exe, + base / ".." / exe, + fs::current_path() / "bin" / exe, + fs::current_path() / "bin" / "Release" / exe, + fs::current_path().parent_path() / "bin" / exe, + fs::current_path().parent_path() / "bin" / "Release" / exe, + }; + for (auto& p : candidates) { + std::error_code ec; + if (fs::exists(p, ec)) + return fs::weakly_canonical(p, ec); } + return exe; +} - std::string normalizeOutput(std::string result) { - // Newlines - { - std::string tmp; - tmp.reserve(result.size()); - for (size_t i = 0; i < result.size(); ++i) { - char c = result[i]; - if (c == '\r') { - // Skip CR; if next is LF, LF will be handled naturally - continue; - } - tmp.push_back(c); +std::string normalizeOutput(std::string result) { + // Newlines + { + std::string tmp; + tmp.reserve(result.size()); + for (size_t i = 0; i < result.size(); ++i) { + char c = result[i]; + if (c == '\r') { + // Skip CR; if next is LF, LF will be handled naturally + continue; } - result.swap(tmp); + tmp.push_back(c); } - // ANSI escape sequences: \x1B[ ... letter - { - std::string tmp; - tmp.reserve(result.size()); - for (size_t i = 0; i < result.size();) { - unsigned char c = static_cast(result[i]); - if (c == 0x1B && i + 1 < result.size() && result[i + 1] == '[') { - // Skip until a letter (m, K, etc.) or end - i += 2; - while (i < result.size()) { - char ch = result[i++]; - if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) - break; - } - } else { - tmp.push_back(static_cast(c)); - ++i; + result.swap(tmp); + } + // ANSI escape sequences: \x1B[ ... letter + { + std::string tmp; + tmp.reserve(result.size()); + for (size_t i = 0; i < result.size();) { + unsigned char c = static_cast(result[i]); + if (c == 0x1B && i + 1 < result.size() && result[i + 1] == '[') { + // Skip until a letter (m, K, etc.) or end + i += 2; + while (i < result.size()) { + char ch = result[i++]; + if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) + break; } + } else { + tmp.push_back(static_cast(c)); + ++i; } - result.swap(tmp); } - return result; + result.swap(tmp); } + return result; +} - std::string runBloch(const std::string& source, const std::string& name, - const std::string& options = "") { - namespace fs = std::filesystem; - fs::path cwd = fs::current_path(); - fs::path blochFile = cwd / name; - std::ofstream ofs(blochFile); - ofs << source; - ofs.close(); +std::string runBloch(const std::string& source, const std::string& name, + const std::string& options = "") { + namespace fs = std::filesystem; + fs::path cwd = fs::current_path(); + fs::path blochFile = cwd / name; + std::ofstream ofs(blochFile); + ofs << source; + ofs.close(); - fs::path blochBin = findBlochBinary(); + fs::path blochBin = findBlochBinary(); - std::string cmd = std::string("\"") + blochBin.string() + "\""; - if (!options.empty()) - cmd += " " + options; - cmd += std::string(" \"") + fs::absolute(blochFile).string() + "\" 2>&1"; - std::string result; - // Redirect stdout/stderr to a file and read it back (more portable than popen on Windows) - fs::path stem = blochFile.stem(); - fs::path outPath = cwd / (stem.string() + ".out"); - std::string redirCmd = cmd + std::string(" > \"") + outPath.string() + "\" 2>&1"; - [[maybe_unused]] int rc = std::system(redirCmd.c_str()); - { - std::ifstream in(outPath); - if (in) { - result.assign((std::istreambuf_iterator(in)), - std::istreambuf_iterator()); - in.close(); - } + std::string cmd = std::string("\"") + blochBin.string() + "\""; + if (!options.empty()) + cmd += " " + options; + cmd += std::string(" \"") + fs::absolute(blochFile).string() + "\" 2>&1"; + std::string result; + // Redirect stdout/stderr to a file and read it back (more portable than popen on Windows) + fs::path stem = blochFile.stem(); + fs::path outPath = cwd / (stem.string() + ".out"); + std::string redirCmd = cmd + std::string(" > \"") + outPath.string() + "\" 2>&1"; + [[maybe_unused]] int rc = std::system(redirCmd.c_str()); + { + std::ifstream in(outPath); + if (in) { + result.assign((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + in.close(); } + } - result = normalizeOutput(std::move(result)); + result = normalizeOutput(std::move(result)); - fs::remove(blochFile); - fs::remove(cwd / (stem.string() + ".qasm")); - fs::remove(cwd / (stem.string() + ".out")); - return result; - } + fs::remove(blochFile); + fs::remove(cwd / (stem.string() + ".qasm")); + fs::remove(cwd / (stem.string() + ".out")); + return result; +} - std::string runBlochCommand(const std::string& options) { - namespace fs = std::filesystem; - fs::path cwd = fs::current_path(); - fs::path blochBin = findBlochBinary(); - fs::path outPath = cwd / "bloch_cli.out"; - std::string cmd = std::string("\"") + blochBin.string() + "\""; - if (!options.empty()) - cmd += " " + options; - cmd += std::string(" > \"") + outPath.string() + "\" 2>&1"; - [[maybe_unused]] int rc = std::system(cmd.c_str()); - std::string result; - { - std::ifstream in(outPath); - if (in) { - result.assign((std::istreambuf_iterator(in)), - std::istreambuf_iterator()); - } +std::string runBlochCommand(const std::string& options) { + namespace fs = std::filesystem; + fs::path cwd = fs::current_path(); + fs::path blochBin = findBlochBinary(); + fs::path outPath = cwd / "bloch_cli.out"; + std::string cmd = std::string("\"") + blochBin.string() + "\""; + if (!options.empty()) + cmd += " " + options; + cmd += std::string(" > \"") + outPath.string() + "\" 2>&1"; + [[maybe_unused]] int rc = std::system(cmd.c_str()); + std::string result; + { + std::ifstream in(outPath); + if (in) { + result.assign((std::istreambuf_iterator(in)), std::istreambuf_iterator()); } - fs::remove(outPath); - return normalizeOutput(std::move(result)); } + fs::remove(outPath); + return normalizeOutput(std::move(result)); } +} // namespace TEST(IntegrationTest, RunsQuantumProgram) { std::string src = R"( @@ -212,7 +210,6 @@ TEST(IntegrationTest, HelpListsAllCliOptions) { EXPECT_NE(output.find("--emit-qasm"), std::string::npos); EXPECT_NE(output.find("--shots"), std::string::npos); EXPECT_NE(output.find("--echo=auto|all|none"), std::string::npos); - EXPECT_NE(output.find("--update"), std::string::npos); } #endif // BLOCH_SKIP_INTEGRATION_TESTS @@ -317,7 +314,7 @@ function main() -> void { EXPECT_EQ(output.find("The '--shots=N' flag will be deprecated"), std::string::npos); } -TEST(IntegrationTest, ShotsFlagStillWorksAndWarns) { +TEST(IntegrationTest, ShotsFlagStillWorks) { std::string src = R"( function main() -> void { @tracked qubit q; @@ -326,7 +323,6 @@ function main() -> void { )"; std::string output = runBloch(src, "shots_flag.bloch", "--shots=4"); EXPECT_NE(output.find("Shots: 4"), std::string::npos); - EXPECT_NE(output.find("The '--shots=N' flag will be deprecated"), std::string::npos); } TEST(IntegrationTest, ShotsAnnotationOverridesFlagAndWarns) { diff --git a/tests/test_lexer.cpp b/tests/test_lexer.cpp index c4b9132..1a0887b 100644 --- a/tests/test_lexer.cpp +++ b/tests/test_lexer.cpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/tests/test_main.cpp b/tests/test_main.cpp index ca563c5..2faa910 100644 --- a/tests/test_main.cpp +++ b/tests/test_main.cpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/tests/test_parser.cpp b/tests/test_parser.cpp index faa407c..548c226 100644 --- a/tests/test_parser.cpp +++ b/tests/test_parser.cpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/tests/test_runtime.cpp b/tests/test_runtime.cpp index 9df303a..21dd396 100644 --- a/tests/test_runtime.cpp +++ b/tests/test_runtime.cpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -423,7 +423,8 @@ TEST(RuntimeTest, TracksVariableMultipleShots) { RuntimeEvaluator eval; eval.execute(*program); for (const auto& vk : eval.trackedCounts()) - for (const auto& vv : vk.second) agg[vk.first][vv.first] += vv.second; + for (const auto& vv : vk.second) + agg[vk.first][vv.first] += vv.second; } ASSERT_EQ(agg["qubit q"]["?"], 5); } diff --git a/tests/test_semantics.cpp b/tests/test_semantics.cpp index 6ea6f8f..9d8a583 100644 --- a/tests/test_semantics.cpp +++ b/tests/test_semantics.cpp @@ -1,4 +1,4 @@ -// Copyright 2025-2026 Akshay Pal (https://bloch-labs.com) +// Copyright 2025-2026 Akshay Pal (https://github.com/akshaysoftware) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/version.txt b/version.txt new file mode 100644 index 0000000..d72f262 --- /dev/null +++ b/version.txt @@ -0,0 +1 @@ +2.0.0-dev