Merge main into feat/blob-eraser-size-stylus-wheel

This commit is contained in:
dotCooCoo committed 2026-11-25 09:46:23 -08:00
commit 9d3bbb8fa6
259 files changed
+18648 -1579

No files matched your search

+135
View File
@@ -0,0 +1,135 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/vectorcraft",
"repository_id": 1398097510,
"producer_workflow_id": null,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
"echelon",
"FredApps",
"skylartaylor"
],
"max_age_seconds": 86400,
"candidate_policy": {
"schema": "craft-nightly-candidate-policy/v3",
"epoch": "vectorcraft-nightly-20261124",
"repository": "storytold/vectorcraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 380135806,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "gate / select legs",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / cache warm (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / test 1/5 (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / test 2/5 (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / test 3/5 (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / test 4/5 (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / test 5/5 (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
},
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_vectorcraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_vectorcraft&branch=main",
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [],
"required_conditions": [
{
"metric": "new_reliability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_maintainability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_coverage",
"comparator": "LT",
"error_threshold": "80"
},
{
"metric": "new_duplicated_lines_density",
"comparator": "GT",
"error_threshold": "3"
},
{
"metric": "new_security_hotspots_reviewed",
"comparator": "LT",
"error_threshold": "100"
}
],
"debt": []
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
"trust": {
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
}
},
"linux-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
"trust": {
"apple_team_id": "DJ6XS33FX8"
}
}
}
}
+72
View File
@@ -0,0 +1,72 @@
name: Nightly check
# The app-side Nightly pieces, checked without a feed run: the Python suites that read the archive,
# plist and signing scripts, the workflow contracts, and (on Windows) the packaging and signing
# PowerShell suites. The producer itself is .github/workflows/nightly.yml; the Apple-silicon bundle
# is built and verified by nightly-macos.yml behind the `full-ci` label.
on:
push:
branches: [main, release]
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"]
pull_request:
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: nightly-check-${{ github.ref }}
cancel-in-progress: true
jobs:
synthetic:
name: Packaging suites and script syntax
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Run the synthetic suites
run: python3 packaging/nightly-tests.py
- name: Parse every nightly shell script
run: |
set -euo pipefail
for script in packaging/nightly-common.sh packaging/linux/nightly.sh packaging/linux/nightly-launch.sh \
packaging/linux/nightly-arch-tar.sh packaging/macos/nightly.sh \
packaging/macos/nightly-lib.sh packaging/macos/nightly-sign.sh packaging/macos/nightly-verify.sh; do
bash -n "$script"
done
- name: Shellcheck
run: |
set -euo pipefail
sudo apt-get update -qq
sudo apt-get install -y -qq shellcheck
shellcheck -x -P packaging packaging/nightly-common.sh packaging/linux/nightly.sh \
packaging/linux/nightly-launch.sh \
packaging/macos/nightly.sh packaging/macos/nightly-lib.sh packaging/macos/nightly-sign.sh \
packaging/macos/nightly-verify.sh
windows:
name: Windows packaging and signing suites
runs-on: windows-latest
timeout-minutes: 20
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Nightly packaging suite
shell: pwsh
run: ./packaging/windows/nightly-package-tests.ps1 -FixtureRoot $env:RUNNER_TEMP
- name: Nightly signing suite
shell: pwsh
run: ./packaging/windows/nightly-signing-tests.ps1 -FixtureRoot $env:RUNNER_TEMP
+90
View File
@@ -0,0 +1,90 @@
name: Nightly macOS build
# Builds the unsigned Apple-silicon VectorCraft Nightly (packaging/macos/nightly.sh) on a hosted
# macOS runner and checks the archive as the Launcher unpacks it, ending with the bundle's version
# query (packaging/macos/nightly-verify.sh --expect unsigned). No secrets and no environment: the real
# Nightly is signed and notarized by the shared release-ref signer (craft-common-actions), which calls
# packaging/macos/nightly-sign.sh.
on:
# macOS runners are shared with release builds and have a monthly minute cap: pull requests run
# this only with the `full-ci` label, never by changed paths. `labeled` so adding it starts a run.
pull_request:
types: [opened, synchronize, reopened, labeled]
workflow_dispatch:
permissions:
contents: read
# A newer push to a labelled PR cancels its older run. Any event that will not build (no `full-ci`
# label, or another label added) gets a group of its own, so it never cancels a real build.
concurrency:
group: nightly-macos-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
build:
name: Nightly .app (aarch64, unsigned)
if: >-
github.event_name == 'workflow_dispatch' ||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
runs-on: macos-15
timeout-minutes: 120
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: 1
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
fetch-depth: 0
# The release's pin (release.yml craft-fonts-ref), so the bundle's notices match a shipped build.
- name: Check out craft-fonts
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- id: rust
uses: storytold/craft-common-actions/actions/rust-channel@main
with:
targets: aarch64-apple-darwin
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: ${{ steps.rust.outputs.toolchain }}
targets: ${{ steps.rust.outputs.targets }}
components: ${{ steps.rust.outputs.components }}
# A version of the prepared Nightly form for this commit; the real one comes from the feed's
# identity job. Only nightly.sh's input checks read it.
- name: Prepare a Nightly identity for this commit
run: |
set -euo pipefail
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
sha="$(git rev-parse HEAD)"
date="$(date -u +%Y-%m-%d)"
{
echo "VECTORCRAFT_BUILD_SHA=$sha"
echo "VECTORCRAFT_BUILD_DATE=$date"
echo "VECTORCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
} >>"$GITHUB_ENV"
- name: Build the unsigned Nightly bundle
env:
VECTORCRAFT_BUILD_CHANNEL: nightly-v1
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
DIST: ${{ runner.temp }}/nightly-dist
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
run: bash packaging/macos/nightly.sh --arch aarch64
- name: Check the archive and the bundle's version
run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$RUNNER_TEMP/nightly-dist/vectorcraft-$VECTORCRAFT_VERSION-macos-aarch64-nightly.zip"
# Keeps the verified unsigned zip briefly for keyless signer tests and hand testing. Unsigned only.
- name: Keep the unsigned archive
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: vectorcraft-nightly-macos-aarch64-unsigned
path: ${{ runner.temp }}/nightly-dist/vectorcraft-${{ env.VECTORCRAFT_VERSION }}-macos-aarch64-nightly.zip
if-no-files-found: error
retention-days: 7
compression-level: 0
+42
View File
@@ -0,0 +1,42 @@
name: VectorCraft release-ref nightly signer
# Enabled for supervised manual dispatch on release. Main/release contents must match.
# A reusable callee does not change context; this must be a real top-level release dispatch.
on:
workflow_dispatch:
inputs:
producer_run_id:
description: Exact untrusted producer Actions run ID
required: true
type: string
producer_run_attempt:
description: Exact untrusted producer Actions run attempt
required: true
type: string
permissions: {}
concurrency:
group: vectorcraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real release branch.
if: >-
github.repository == 'storytold/vectorcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the existing release environment and export keys in its signing step.
+34
View File
@@ -0,0 +1,34 @@
name: VectorCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
on:
workflow_dispatch:
permissions:
contents: read
jobs:
unsigned:
# Actual context guards only; no inherited/platform secrets.
if: >-
github.repository == 'storytold/vectorcraft' &&
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
# no OIDC, attestation write, release environment or platform secrets in compilation.
permissions:
contents: read
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
app-name: vectorcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
# Linux/macOS signer (#342).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
+7
View File
@@ -7,3 +7,10 @@ plan/
.DS_Store
# A craft-fonts checkout for CRAFT_FONTS_DIR (CI and release workflows check it out here)
/craft-fonts
# The Python packaging helpers' bytecode: `nightly-archive.py` imports `nightly_paths`, and the
# producer's clean-tree check runs after a local packaging run would have written it.
__pycache__/
# The shared nightly workflow's scratch checkouts and inputs: the producer requires a clean tree.
/.nightly-tools
/.nightly-input
/craft-i18n
+16
View File
@@ -51,6 +51,10 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.vectorcraft.svg` | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for VectorCraft, vectorised and rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon (engraved dragon) |
| `assets/app-icon/vectorcraft-1024.png` | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for VectorCraft, vectorised and rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon (engraved dragon) |
| `assets/app-icon/vectorcraft-macos-512.png` | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for VectorCraft, vectorised and rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon (engraved dragon) |
| `assets/app-icon/vectorcraft-nightly-1024.png` | Project owner (ArtCraft team) | Recoloured from the stable app tile by `packaging/nightly-icons.py`, original artwork drawn in ArtCraft for VectorCraft | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly `.app` master: the full tile with Apple's margin, 1024 px |
| `assets/app-icon/vectorcraft-nightly.icns` | Project owner (ArtCraft team) | Recoloured from the stable app tile by `packaging/nightly-icons.py`, original artwork drawn in ArtCraft for VectorCraft | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly macOS icon set, 16 to 1024 px |
| `assets/app-icon/vectorcraft-nightly.ico` | Project owner (ArtCraft team) | Recoloured from the stable app tile by `packaging/nightly-icons.py`, original artwork drawn in ArtCraft for VectorCraft | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly Windows icons, 16 to 256 px |
| `assets/app-icon/vectorcraft-nightly.png` | Project owner (ArtCraft team) | Recoloured from the stable app tile by `packaging/nightly-icons.py`, original artwork drawn in ArtCraft for VectorCraft | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | Nightly feed art and window icon, 1024 px |
| `assets/app-icon/vectorcraft-small.svg` | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for VectorCraft, vectorised and rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon (engraved dragon) |
| `assets/app-icon/vectorcraft.icns` | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for VectorCraft, vectorised and rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon (engraved dragon) |
| `assets/app-icon/vectorcraft.ico` | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for VectorCraft, vectorised and rendered by `packaging/icons.sh` | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | App icon (engraved dragon) |
@@ -139,12 +143,14 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-arrow-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Selection and Direct Selection arrows' fill, painted black or white under their outline |
| `assets/icons/dc-arrow-tip.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-arrow-up.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-artboard.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-artboard-options.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-artboards.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-blend.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-blend-align-page.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-blend-align-path.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-bloat.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-blob-brush.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-cap-butt.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-cap-round.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-cap-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
@@ -223,6 +229,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-live-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-mask-none.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-measure.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-measure-inspect.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-mesh.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-mirror-cut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-new-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
@@ -241,6 +248,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-para-numbers.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: the digits 1, 2 and 3, each before a line | MIT OR Apache-2.0 | |
| `assets/icons/dc-para-right.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-para-rtl.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-parametric-shape.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-path-eraser.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-pathfinder.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-perspective-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
@@ -258,32 +266,38 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-place-symbol.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-polar-grid.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-polygon.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-print-tiling.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-pucker.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-puppet.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-quick-pen.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a line and a half circle with a dot at each point) | MIT OR Apache-2.0 | |
| `assets/icons/dc-rearrange.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-recolor-arrow.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a right arrow, a Recolor Artwork row that is recolored) | MIT OR Apache-2.0 | |
| `assets/icons/dc-recolor-arrow-off.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a dashed line without a head, a Recolor Artwork row that is excluded) | MIT OR Apache-2.0 | |
| `assets/icons/dc-rect.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-rect-cut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-rect-grid.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-reference-point.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-remove-brush.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-reshape.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-reverse.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-rotate.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-rotate-view.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-rounded-rect.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-rule-evenodd.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-rule-nonzero.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-scale.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-scallop.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-screen-mode.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-selection.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-shape-builder.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-shaper.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-shared-edge.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-shear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-slice-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-slice.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-slide-anchor.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-smooth.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-spiral.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-stroke-center.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-stroke-inside.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-stroke-outside.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
@@ -301,6 +315,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-symbol-sprayer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-symbol-stainer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-symbol-styler.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-tangent-circle.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-touch-type.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-transform-panel.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-transparency.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
@@ -311,6 +326,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-type-vertical.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-type-vertical-area.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-type-vertical-path.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-warp.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-width-profile.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-width.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-wrinkle.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
Generated
+80 -80
View File
@@ -1134,7 +1134,7 @@ dependencies = [
[[package]]
name = "craft"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-automation",
"craft-behavior",
@@ -1175,7 +1175,7 @@ dependencies = [
[[package]]
name = "craft-affinity"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"crc32fast",
"flate2",
@@ -1186,7 +1186,7 @@ dependencies = [
[[package]]
name = "craft-appkit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"block2 0.6.2",
"objc2-app-kit 0.3.2",
@@ -1196,7 +1196,7 @@ dependencies = [
[[package]]
name = "craft-atomic"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"rustix 1.1.6",
]
@@ -1204,7 +1204,7 @@ dependencies = [
[[package]]
name = "craft-automation"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"base64 0.23.1",
"craft-behavior",
@@ -1229,7 +1229,7 @@ dependencies = [
[[package]]
name = "craft-behavior"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"accesskit",
"bitflags 2.13.2",
@@ -1247,7 +1247,7 @@ dependencies = [
[[package]]
name = "craft-browse"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-behavior",
"craft-docpath",
@@ -1265,7 +1265,7 @@ dependencies = [
[[package]]
name = "craft-cdr"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"crc32fast",
"flate2",
@@ -1274,7 +1274,7 @@ dependencies = [
[[package]]
name = "craft-cloud-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"egui",
]
@@ -1282,7 +1282,7 @@ dependencies = [
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"md-5",
"rayon",
@@ -1291,12 +1291,12 @@ dependencies = [
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
[[package]]
name = "craft-color-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-behavior",
"craft-cms",
@@ -1316,7 +1316,7 @@ dependencies = [
[[package]]
name = "craft-control"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"getrandom 0.3.4",
"serde",
@@ -1326,7 +1326,7 @@ dependencies = [
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"rayon",
]
@@ -1334,7 +1334,7 @@ dependencies = [
[[package]]
name = "craft-dialogs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"block2 0.6.2",
"craft-atomic",
@@ -1359,7 +1359,7 @@ dependencies = [
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"serde",
]
@@ -1367,7 +1367,7 @@ dependencies = [
[[package]]
name = "craft-draw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1386,7 +1386,7 @@ dependencies = [
[[package]]
name = "craft-dxf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-codepage",
"encoding_rs",
@@ -1398,12 +1398,12 @@ dependencies = [
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"fontique",
"harfrust 0.13.3",
@@ -1418,7 +1418,7 @@ dependencies = [
[[package]]
name = "craft-font-manager"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-behavior",
"craft-font-catalog",
@@ -1437,7 +1437,7 @@ dependencies = [
[[package]]
name = "craft-font-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"cap-primitives",
"craft-atomic",
@@ -1459,12 +1459,12 @@ dependencies = [
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
[[package]]
name = "craft-gif"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"gif",
]
@@ -1472,7 +1472,7 @@ dependencies = [
[[package]]
name = "craft-gzip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"flate2",
]
@@ -1480,7 +1480,7 @@ dependencies = [
[[package]]
name = "craft-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"bitflags 2.13.2",
"craft-i18n",
@@ -1493,7 +1493,7 @@ dependencies = [
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"chrono",
"fixed_decimal",
@@ -1521,7 +1521,7 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-dds",
"craft-jpeg",
@@ -1548,7 +1548,7 @@ dependencies = [
[[package]]
name = "craft-imaging"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1566,7 +1566,7 @@ dependencies = [
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"thiserror 2.0.21",
]
@@ -1574,7 +1574,7 @@ dependencies = [
[[package]]
name = "craft-jxl"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"brotli-decompressor 5.0.3",
"jixel",
@@ -1585,7 +1585,7 @@ dependencies = [
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-host",
"craft-i18n",
@@ -1600,7 +1600,7 @@ dependencies = [
[[package]]
name = "craft-layers"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-behavior",
"craft-i18n",
@@ -1614,7 +1614,7 @@ dependencies = [
[[package]]
name = "craft-menu"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-behavior",
"craft-host",
@@ -1632,7 +1632,7 @@ dependencies = [
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"brotli-decompressor 6.3.2",
"chrono",
@@ -1644,7 +1644,7 @@ dependencies = [
[[package]]
name = "craft-metafile"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"encoding_rs",
"image",
@@ -1655,7 +1655,7 @@ dependencies = [
[[package]]
name = "craft-mime"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"chrono",
"craft-codepage",
@@ -1665,7 +1665,7 @@ dependencies = [
[[package]]
name = "craft-pages"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -1681,7 +1681,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"hayro-interpret",
"hayro-syntax",
@@ -1693,7 +1693,7 @@ dependencies = [
[[package]]
name = "craft-platform"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"async-channel",
"async-io",
@@ -1724,7 +1724,7 @@ dependencies = [
[[package]]
name = "craft-plotter"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"kurbo 0.13.1",
"thiserror 2.0.21",
@@ -1733,7 +1733,7 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-behavior",
"craft-host",
@@ -1757,7 +1757,7 @@ dependencies = [
[[package]]
name = "craft-proof"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"log",
"miniz_oxide 0.9.1",
@@ -1768,7 +1768,7 @@ dependencies = [
[[package]]
name = "craft-ps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-eps",
"flate2",
@@ -1782,7 +1782,7 @@ dependencies = [
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"encoding_rs",
"flate2",
@@ -1793,7 +1793,7 @@ dependencies = [
[[package]]
name = "craft-quit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"dispatch2",
"egui",
@@ -1806,7 +1806,7 @@ dependencies = [
[[package]]
name = "craft-review"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"base64 0.23.1",
"craft-behavior",
@@ -1825,7 +1825,7 @@ dependencies = [
[[package]]
name = "craft-settings"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-atomic",
"craft-host",
@@ -1842,7 +1842,7 @@ dependencies = [
[[package]]
name = "craft-stream-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"fax",
"hayro-ccitt",
@@ -1853,7 +1853,7 @@ dependencies = [
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-image-codecs",
"craft-xml",
@@ -1874,7 +1874,7 @@ dependencies = [
[[package]]
name = "craft-table"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -1886,7 +1886,7 @@ dependencies = [
[[package]]
name = "craft-text"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-behavior",
"craft-font-manager",
@@ -1911,7 +1911,7 @@ dependencies = [
[[package]]
name = "craft-theme"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"bitflags 2.13.2",
"craft-tracked",
@@ -1926,7 +1926,7 @@ dependencies = [
[[package]]
name = "craft-theme-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-atomic",
"craft-behavior",
@@ -1941,7 +1941,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1951,7 +1951,7 @@ dependencies = [
[[package]]
name = "craft-time"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1960,7 +1960,7 @@ dependencies = [
[[package]]
name = "craft-timeline"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -1975,12 +1975,12 @@ dependencies = [
[[package]]
name = "craft-tracked"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-cloud-ui",
"craft-ui-canvas",
@@ -1994,7 +1994,7 @@ dependencies = [
[[package]]
name = "craft-ui-canvas"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-behavior",
"craft-i18n",
@@ -2010,7 +2010,7 @@ dependencies = [
[[package]]
name = "craft-ui-contract"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"accesskit",
"craft-behavior",
@@ -2048,7 +2048,7 @@ dependencies = [
[[package]]
name = "craft-ui-macros"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -2059,7 +2059,7 @@ dependencies = [
[[package]]
name = "craft-ui-panels"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2077,7 +2077,7 @@ dependencies = [
[[package]]
name = "craft-ui-patterns"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2098,7 +2098,7 @@ dependencies = [
[[package]]
name = "craft-ui-shell"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2119,7 +2119,7 @@ dependencies = [
[[package]]
name = "craft-ui-widgets"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2138,7 +2138,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"chrono",
"craft-host",
@@ -2167,7 +2167,7 @@ dependencies = [
[[package]]
name = "craft-vectorcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"flate2",
"serde",
@@ -2178,7 +2178,7 @@ dependencies = [
[[package]]
name = "craft-wayland"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"raw-window-handle",
"wayland-backend",
@@ -2188,7 +2188,7 @@ dependencies = [
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"js-sys",
"serde_json",
@@ -2199,7 +2199,7 @@ dependencies = [
[[package]]
name = "craft-win32"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"winsafe",
]
@@ -2207,7 +2207,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"craft-appkit",
"craft-atomic",
@@ -2239,7 +2239,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -3507,7 +3507,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"brotli",
"hayro-postscript",
@@ -3516,7 +3516,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -3534,7 +3534,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -3552,12 +3552,12 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -4488,7 +4488,7 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"base64 0.22.1",
"bumpalo",
@@ -4645,7 +4645,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b"
dependencies = [
"arrayvec",
"kurbo 0.13.1",
+34 -34
View File
@@ -11,44 +11,44 @@ rust-version = "1.95"
repository = "https://github.com/storytold/vectorcraft"
[workspace.dependencies]
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
# WMF, EMF and EMF+ reader (craft-libs#778).
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
# The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names
# the members it imports.
craft = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
# Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui
# without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes.
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -191,13 +191,13 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
+1 -1
View File
@@ -27,7 +27,7 @@ log = { workspace = true }
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b", version = "0.1.0" }
wasm-bindgen = "0.2"
serde_json = { workspace = true }
+1 -1
View File
@@ -45,7 +45,7 @@ winreg = "0.55"
# GPU that shows it: drawing on a GPU without a monitor reset the display driver. Safe wrappers over
# Win32 (MIT); the `user` feature is User32.dll only. Only the wgpu renderer chooses an adapter.
winsafe = { version = "0.0.29", default-features = false, features = ["user"], optional = true }
winsafe = { version = "0.0.29", default-features = false, features = ["user", "shell"], optional = true }
# Waits for Direct3D 12's adapter list before the window starts (src/gpu.rs, #4150). MIT OR
# Apache-2.0, already in the build through eframe.
pollster = "1"
+61 -9
View File
@@ -1,24 +1,67 @@
//! Windows only: embed the app icon and version info (VERSIONINFO) into `vectorcraft.exe`.
//! Windows only: embed the app icon and version info (VERSIONINFO) into `vectorcraft.exe`. Everywhere,
//! fix the build's channel and the version it reports.
//!
//! On every other target this does nothing. A missing resource compiler is a warning, so a
//! cross-compile from macOS or Linux still links, unless `VECTORCRAFT_REQUIRE_WINRES=1` turns it into
//! an error (for release builds).
//! `VECTORCRAFT_BUILD_CHANNEL=nightly-v1` makes a Nightly build and needs an exact feed identity in
//! `VECTORCRAFT_VERSION` (the shared nightly workflow's name) or `VECTORCRAFT_OVERRIDE_VERSION` (what
//! this app's own packaging passes to cargo): `X.Y.Z-nightly.YYYYMMDD.<run>.<attempt>.g<sha12>`. Unset,
//! empty or `stable` means the stable build; anything else is an error.
//!
//! On non-Windows targets the resource half does nothing. A missing resource compiler is a warning, so
//! a cross-compile from macOS or Linux still links, unless `VECTORCRAFT_REQUIRE_WINRES=1` turns it into
//! an error (for release and nightly builds).
#[path = "src/build_channel.rs"]
mod build_channel;
fn main() -> Result<(), String> {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=../../assets/app-icon/vectorcraft.ico");
println!("cargo:rerun-if-env-changed=VECTORCRAFT_REQUIRE_WINRES");
println!("cargo:rustc-check-cfg=cfg(vectorcraft_nightly_v1)");
println!("cargo:rerun-if-env-changed=VECTORCRAFT_BUILD_CHANNEL");
println!("cargo:rerun-if-env-changed=VECTORCRAFT_VERSION");
println!("cargo:rerun-if-env-changed=VECTORCRAFT_OVERRIDE_VERSION");
let nightly = match std::env::var("VECTORCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=vectorcraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
Ok(other) => return Err(format!("unsupported VECTORCRAFT_BUILD_CHANNEL {other:?} (expected stable or nightly-v1)")),
Err(std::env::VarError::NotUnicode(_)) => return Err("VECTORCRAFT_BUILD_CHANNEL is not valid Unicode".to_string()),
};
// The stable build reports its package version, as it always has.
let built_version = if nightly {
match feed_identity() {
Some(version) if build_channel::is_nightly_version(&version) => version,
_ => {
return Err(
"nightly-v1 requires an explicit VECTORCRAFT_VERSION feed identity (X.Y.Z-nightly.YYYYMMDD.<run>.<attempt>.g<sha12>)".to_string()
);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo:rustc-env=VECTORCRAFT_BUILT_VERSION={built_version}");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return Ok(());
}
println!("cargo:rerun-if-changed=../../assets/app-icon/vectorcraft.ico");
println!("cargo:rerun-if-changed=../../assets/app-icon/vectorcraft-nightly.ico");
println!("cargo:rerun-if-env-changed=VECTORCRAFT_REQUIRE_WINRES");
let mut res = winresource::WindowsResource::new();
res.set_icon("../../assets/app-icon/vectorcraft.ico")
.set("ProductName", "VectorCraft")
.set("FileDescription", "VectorCraft vector illustration editor")
res.set_icon(build_channel::windows_icon_path(nightly))
.set("ProductName", if nightly { "VectorCraft Nightly" } else { "VectorCraft" })
.set("FileDescription", if nightly { "VectorCraft Nightly vector illustration editor" } else { "VectorCraft vector illustration editor" })
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) the VectorCraft authors. MIT OR Apache-2.0.")
.set("OriginalFilename", "vectorcraft.exe")
.set("InternalName", "vectorcraft");
if nightly {
// The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
res.set("ProductVersion", &built_version);
}
if let Err(e) = res.compile() {
if std::env::var_os("VECTORCRAFT_REQUIRE_WINRES").is_some() {
return Err(format!("embedding Windows resources failed: {e}"));
@@ -27,3 +70,12 @@ fn main() -> Result<(), String> {
}
Ok(())
}
/// The feed identity from `VECTORCRAFT_VERSION`, else `VECTORCRAFT_OVERRIDE_VERSION`: the shared
/// nightly workflow sets the first, this app's own packaging scripts the second.
fn feed_identity() -> Option<String> {
["VECTORCRAFT_VERSION", "VECTORCRAFT_OVERRIDE_VERSION"]
.into_iter()
.filter_map(|name| std::env::var(name).ok().filter(|value| !value.is_empty()))
.next()
}
+14 -4
View File
@@ -1,5 +1,6 @@
#[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))]
use super::gpu;
use super::nightly_session;
use super::prefs::{flush, save_tick};
#[cfg(not(target_os = "macos"))]
use super::single_instance;
@@ -95,10 +96,17 @@ impl eframe::App for App {
// A ready update installs once the process has exited. The macOS exit below skips
// dropping the app, so the helper is started here.
self.app.start_pending_update();
// Every quit reaches this hook, including a macOS Cmd+Q, which ends the process inside
// AppKit's terminate before `run_native` returns: the nightly session record is finished
// here, and the return path after the event loop is then a no-op.
nightly_session::finish_once();
// Dropping the app can wait for the clipboard handles to let go: the windows leave the
// screen first (`quit_windows`).
#[cfg(not(any(target_os = "macos", windows)))]
super::quit_windows::before_teardown(self.winit_window.as_deref());
// Plug-ins still loading end before the launch marker does (the macOS exit below skips
// dropping the app).
self.app.session.cancel_plugin_loads();
end_before_teardown(self.frames);
}
}
@@ -159,8 +167,9 @@ impl App {
// dialog is open: what asked for it runs again on its document when it answers. They also
// wait for the choice about a stopped plug-in, so they open after the plug-ins it loads, as
// do the command line's files held back for it. Files later launches handed over before the
// choice ended in Safe Mode open in a new app with plug-ins.
if !self.app.file_dialog_open() && !safe_mode::choosing(&self.app) {
// choice ended in Safe Mode open in a new app with plug-ins. They wait while plug-ins load
// as well, since a plug-in may be what reads them.
if !self.app.file_dialog_open() && !safe_mode::choosing(&self.app) && !self.app.session.plugins_loading() {
let held = std::mem::take(&mut self.held_files);
#[cfg(target_os = "macos")]
let files = open_documents::take();
@@ -210,9 +219,10 @@ pub(crate) fn bring_window_forward(ctx: &egui::Context) {
}
/// Open the command line's `files` now, or, while the choice about a stopped plug-in is up
/// ([`safe_mode::choosing`]), return them to open once it is made, with the plug-ins it loads.
/// ([`safe_mode::choosing`]) or plug-ins are still loading (a plug-in may be what reads one),
/// return them to open once it is made and they have loaded.
pub(crate) fn open_or_hold(app: &mut VectorcraftApp, files: Vec<String>) -> Vec<String> {
if safe_mode::choosing(app) {
if safe_mode::choosing(app) || app.session.plugins_loading() {
return files;
}
open_files(app, files);
+58
View File
@@ -0,0 +1,58 @@
//! The build-time nightly identity shared by the build script and its pure regression tests.
/// A nightly feed identity: `X.Y.Z-nightly.YYYYMMDD.<run>.<attempt>.g<sha12>`, exactly.
pub fn is_nightly_version(version: &str) -> bool {
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let base: Vec<_> = base.split('.').collect();
let parts: Vec<_> = suffix.split('.').collect();
base.len() == 3
&& base.iter().all(|s| digits(s))
&& parts.len() == 4
&& parts[0].len() == 8
&& digits(parts[0])
&& digits(parts[1])
&& digits(parts[2])
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
pub fn windows_icon_path(nightly: bool) -> &'static str {
if nightly { "../../assets/app-icon/vectorcraft-nightly.ico" } else { "../../assets/app-icon/vectorcraft.ico" }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
assert_eq!(windows_icon_path(false), "../../assets/app-icon/vectorcraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/vectorcraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.24.1-nightly.20261124.17.1.gabcdef012345"));
for invalid in [
"",
"0.24.1",
"0.24.1-nightly",
"0.24.1-nightly.20261124",
"0.24.1-nightly.20261124.17.1.gABCDEF012345",
"0.24.1-nightly.20261124.17.1.gabcdef012345\n",
] {
assert!(!is_nightly_version(invalid), "{invalid:?}");
}
}
#[test]
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
for invalid in [
"../0.24.1-nightly.20261124.1.1.gabcdef012345",
"0.24.1-nightly.20261124.1.1.gabcdef012345/other",
"0.24.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
+76
View File
@@ -0,0 +1,76 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a
//! stable build, and a nightly build refuses to start without its profile.
use crate::launch_profile::Profile;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub const COMPILED: BuildFlavor = if cfg!(vectorcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open VectorCraft Nightly from ArtCraft Launcher".to_string()),
(BuildFlavor::Stable, true) => Err("This is a stable VectorCraft build; nightly-v1 requires the nightly build".to_string()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
/// `--version` and `-V` on their own, before any other argument is read.
pub fn version_query(args: &[OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
match flavor {
BuildFlavor::Stable => stable.to_string(),
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
assert!(!needs_native_error(BuildFlavor::Stable, true));
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
assert!(require_profile(BuildFlavor::NightlyV1, &Profile::Stable).is_err());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.24.1"), "0.24.1");
assert_eq!(version(BuildFlavor::NightlyV1, "0.24.1"), "0.24.1 (nightly-v1)");
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
+1 -1
View File
@@ -683,7 +683,7 @@ impl Startup {
return LeftOut::default();
}
};
let (record, crash) = StartRecord::begin(previous, env!("CARGO_PKG_VERSION"), preference_name(preference));
let (record, crash) = StartRecord::begin(previous, vectorcraft_ui_egui::os_window::version(), preference_name(preference));
let left_out = record.left_out(crash.clone(), explicit);
match &crash {
Some(Crash::Adapter { key, name }) => {
+1 -1
View File
@@ -137,7 +137,7 @@ impl Facts {
let or_unknown = |v: &Option<String>| v.clone().unwrap_or_else(|| "unknown".to_string());
format!(
"VectorCraft {} on {} {}\nWindow system: {}; desktop: {}; session type: {}; Flatpak: {}\nGraphics: {}; {}\n",
env!("CARGO_PKG_VERSION"),
vectorcraft_ui_egui::os_window::version(),
std::env::consts::OS,
std::env::consts::ARCH,
self.window_system,
+272
View File
@@ -0,0 +1,272 @@
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
//! Stable launches retain their original arguments and directory policy.
//!
//! The protocol is `vectorcraft --launch-profile nightly-v1 --profile-root <abs> -- [files…]`: the
//! selector and the root are separate tokens, exactly once each, and everything after `--` is a file
//! even when it looks like one of them. The Launcher's version check
//! (`… --version`) is answered before the root is validated or touched.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".to_string())
}
/// Recognize only the agreed literal selector/root pair before `--`. No filesystem or startup hook
/// runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".to_string());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or_else(|| "the profile selector/root needs a value".to_string())?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".to_string());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".to_string());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".to_string());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".to_string());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".to_string()),
_ => Err("--launch-profile and --profile-root must be supplied together".to_string()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly root
/// validator, so its portable and config resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
crate::profile_root::validate(root, env, exe, crate::prefs_dir::profile::ensure_writable)
}
/// The arguments a child of this process starts with: a nightly launch hands its profile on, so the
/// child opens the same private profile instead of being refused ("Open VectorCraft Nightly…"), and
/// `--` keeps a file whose name starts with '-' a file. Stable's child arguments are unchanged.
pub fn child_args(files: &[String]) -> Vec<OsString> {
child_args_for(current(), files)
}
fn child_args_for(profile: &Profile, files: &[String]) -> Vec<OsString> {
let mut args: Vec<OsString> = match profile {
Profile::Stable => Vec::new(),
Profile::NightlyV1(root) => {
vec![OsString::from("--launch-profile"), OsString::from(VERSION), OsString::from("--profile-root"), root.clone().into_os_string()]
}
};
args.push(OsString::from("--"));
args.extend(files.iter().map(OsString::from));
args
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\vectorcraft" } else { "/nightly-data/profiles/vectorcraft" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
for argv in [args(&[]), args(&["--new-instance", "a.svg"]), args(&["--", "--launch-profile", "file.svg"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
}
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "art with spaces.svg"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "art with spaces.svg"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "../escape", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
] {
assert!(parse(argv.clone()).is_err(), "{argv:?}");
}
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".to_string())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
}
#[test]
fn a_joined_flag_form_is_refused() {
for joined in [format!("--launch-profile={VERSION}"), format!("--profile-root={}", absolute())] {
let argv = vec![OsString::from(joined), OsString::from("--")];
assert!(parse(argv).is_err());
}
}
#[test]
fn a_stable_child_gets_the_file_delimiter_only() {
let child = child_args_for(&Profile::Stable, &["a file.svg".to_string(), "--looks-like-a-flag".to_string()]);
assert_eq!(child, args(&["--", "a file.svg", "--looks-like-a-flag"]));
}
#[test]
fn a_nightly_child_inherits_the_selected_profile() {
let root = PathBuf::from(absolute());
let child = child_args_for(&Profile::NightlyV1(root.clone()), &["art.svg".to_string()]);
let expected = vec![
OsString::from("--launch-profile"),
OsString::from(VERSION),
OsString::from("--profile-root"),
root.into_os_string(),
OsString::from("--"),
OsString::from("art.svg"),
];
assert_eq!(child, expected);
// The child's own parse finds the same profile and the file list.
let launch = parse(child).unwrap();
assert!(launch.profile.is_nightly());
assert_eq!(launch.args, args(&["--", "art.svg"]));
}
}
+240 -40
View File
@@ -28,6 +28,9 @@
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
mod automation_args;
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod clipboard;
#[cfg(feature = "wgpu")]
mod compositor_gpu;
@@ -36,6 +39,7 @@ mod display_profile;
#[cfg(feature = "wgpu")]
mod gpu;
mod hang_watch;
mod launch_profile;
#[cfg(target_os = "linux")]
mod linux_stylus;
mod logging;
@@ -46,11 +50,14 @@ mod mac_fonts;
mod mac_tablet;
#[cfg(target_os = "macos")]
mod mac_window;
mod nightly_session;
#[cfg(target_os = "macos")]
mod open_documents;
mod prefs_dir;
mod presentation;
mod printing;
mod process_identity;
mod profile_root;
#[cfg(not(any(target_os = "macos", windows)))]
mod quit_windows;
#[cfg(not(target_os = "macos"))]
@@ -101,9 +108,6 @@ use prefs::{load_prefs, log_dir, open_store, prefs_enabled};
const DEFAULT_SIZE: [f32; 2] = [1440.0, 900.0];
const MIN_SIZE: [f32; 2] = [800.0, 500.0];
/// The app id every OS window carries; it matches `packaging/linux/ai.storyteller.vectorcraft.desktop`.
const WINDOW_APP_ID: &str = "ai.storyteller.vectorcraft";
/// The window, Dock, taskbar and app-switcher icon (`assets/app-icon/`, see its README). macOS gets
/// the version with Apple's transparent margin; elsewhere the full-bleed tile. The app ID matches
/// `packaging/linux/ai.storyteller.vectorcraft.desktop` so Wayland docks find the launcher icon.
@@ -137,7 +141,7 @@ fn adapter_summary(info: &eframe::wgpu::AdapterInfo) -> String {
fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("VectorCraft")
.with_title(vectorcraft_ui_egui::os_window::name())
.with_inner_size(DEFAULT_SIZE)
.with_min_inner_size(MIN_SIZE)
.with_drag_and_drop(true)
@@ -146,11 +150,35 @@ fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
.with_titlebar_shown(false)
.with_title_shown(false)
.with_icon(app_icon())
.with_app_id(WINDOW_APP_ID),
.with_app_id(vectorcraft_ui_egui::os_window::app_id()),
// A nightly keeps its own window state in its private profile; a stable build lets eframe
// keep it where it always did.
persistence_path: nightly_window_state(),
..Default::default()
}
}
/// Where eframe keeps its own saved state, if its persistence feature is ever on: a folder of its
/// own inside the nightly profile ([`nightly_root`]), never the file craft's window placement is in
/// (`<profile>/window.json`, which eframe would treat as a folder) and never the stable app's.
fn nightly_window_state() -> Option<std::path::PathBuf> {
nightly_root().map(|root| root.join("eframe"))
}
/// The saved window placement (the framework's `window.json`): beside the preferences, as it always
/// was, or inside a nightly's private profile so the two channels never move each other's windows.
fn placement_store() -> Store {
match nightly_root() {
Some(root) => Store::at(&root.join(craft::window::restore::FILE_NAME)),
None => Store::open("vectorcraft"),
}
}
/// This launch's private Nightly profile, when it is one.
fn nightly_root() -> Option<&'static std::path::Path> {
launch_profile::current().root()
}
struct App {
app: VectorcraftApp,
/// The preferences, written through [`prefs::save_tick`] and on exit.
@@ -277,7 +305,14 @@ fn read_command_line(
"--new-instance" => new_instance = true,
"--safe-mode" => safe_mode = true,
"--version" => {
println!("vectorcraft {}", env!("CARGO_PKG_VERSION"));
// A nightly says what it is, like the early answer; a stable build's line is unchanged.
let line = match build_flavor::COMPILED {
build_flavor::BuildFlavor::Stable => format!("vectorcraft {}\n", vectorcraft_ui_egui::os_window::version()),
build_flavor::BuildFlavor::NightlyV1 => {
format!("VectorCraft {}\n", build_flavor::version(build_flavor::COMPILED, vectorcraft_ui_egui::os_window::version()))
}
};
let _ = std::io::Write::write_all(&mut std::io::stdout(), line.as_bytes());
return Err(std::process::ExitCode::SUCCESS);
}
// Before anything starts, like `--version`: from a terminal or an agent's shell the app
@@ -332,12 +367,158 @@ fn opens_through_xwayland(pref: Option<&str>) -> bool {
true
}
fn main() -> std::process::ExitCode {
// Windows: the update helper is a copy of this program started with `--finish-update`.
#[cfg(windows)]
if let Some(result) = craft::update::self_update::finish(&vectorcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
/// The nightly channel this build is, as a string for the log.
fn channel_name() -> &'static str {
match build_flavor::COMPILED {
build_flavor::BuildFlavor::Stable => "stable",
build_flavor::BuildFlavor::NightlyV1 => launch_profile::VERSION,
}
}
/// Says why a nightly launch was refused, then exits 2. A window could not have shown it yet: this
/// app has no message box of its own before eframe starts (its dialogs are egui windows), so the
/// text goes to standard error, which a Launcher launch records. The desktop-session test still
/// decides whether a daily user would have seen it, for the message's wording.
fn report_launch_profile_error(error: &str) {
eprintln!("VectorCraft launch profile: {error}");
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
eprintln!("VectorCraft Nightly: open it from ArtCraft Launcher, which starts it in its own profile");
}
}
/// Selects the immutable launch profile before any startup service or side effect, and returns the
/// arguments the rest of `main` reads. `None` means the process ends here (`--version` answered).
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
// The trusted Launcher protocol is decided before the logger, updates, fonts or any saved state.
let argv: Vec<_> = std::env::args_os().skip(1).collect();
// A nightly answers its version before root validation, process identity, IPC or any window:
// plain `--version`/`-V`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`. A stable build leaves the answer to `read_command_line`, exactly as before.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
{
use std::io::Write as _;
let line = format!("VectorCraft {}\n", build_flavor::version(build_flavor::COMPILED, env!("VECTORCRAFT_BUILT_VERSION")));
let _ = std::io::stdout().write_all(line.as_bytes());
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
Ok(launch)
})
.and_then(|launch| {
launch_profile::prepare(launch, |root| {
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
})
})
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let nightly = early.profile.is_nightly();
let identity =
if nightly { vectorcraft_ui_egui::os_window::LaunchIdentity::NightlyV1 } else { vectorcraft_ui_egui::os_window::LaunchIdentity::Stable };
let install = launch_profile::install(early.profile).and_then(|()| {
// Every data path follows the selected profile from here on: settings, logs, recovery, the
// user's libraries, plug-ins, caches and the single-instance record.
if let Some(root) = launch_profile::current().root() {
prefs_dir::profile::install_data_root(root.to_path_buf())?;
}
vectorcraft_ui_egui::os_window::select_identity(identity)
});
if let Err(error) = install {
report_launch_profile_error(&error);
std::process::exit(2);
}
if let Err(error) = vectorcraft_ui_egui::os_window::set_version(env!("VECTORCRAFT_BUILT_VERSION")) {
report_launch_profile_error(&error);
std::process::exit(2);
}
// A nightly's taskbar identity, before the first window: otherwise Windows groups it with the
// stable app and the Launcher's own entry.
if let Err(error) =
process_identity::initialize(nightly, vectorcraft_ui_egui::os_window::id_for(vectorcraft_ui_egui::os_window::LaunchIdentity::NightlyV1))
{
report_launch_profile_error(&error.to_string());
// The window's identity, not the profile, failed: main's own failure status (1).
std::process::exit(1);
}
Some(early.args)
}
/// The arguments the rest of `main` reads: a nightly's profile tokens were consumed by
/// `prepare_launch`, so what is left is `--` and the files to open. A stable launch reads its
/// arguments exactly as it always did.
fn launch_arguments(nightly: bool, arguments: &[std::ffi::OsString]) -> Vec<String> {
if nightly { arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect() } else { std::env::args().skip(1).collect() }
}
/// The control channel's port, and the token's notice with the token itself.
type ControlChannel = (Option<u16>, Option<(String, String)>);
/// Port and token of the control channel, or the message to print. A nightly is started by the
/// Launcher, never by an agent, so the channel and its inherited environment stay off: no token
/// file is read and nothing listens.
fn control_channel(control: &automation_args::ControlArg, nightly: bool) -> Result<ControlChannel, String> {
if nightly {
if control.options().port.is_some() || std::env::var_os("VECTORCRAFT_CONTROL_PORT").is_some() {
eprintln!("vectorcraft: the control channel is off in a nightly build");
}
return Ok((None, None));
}
let options = ControlOptions::resolve(control.options(), &EnvNames::for_app("VECTORCRAFT")).map_err(|e| e.to_string())?;
let port = options.port;
// Read before the window opens: a token file that can't be read keeps the app from starting
// rather than leaving the channel open without one.
let token = port.map(|_| options.server_token()).transpose().map_err(|e| e.to_string())?;
Ok((port, token.map(|token| (options.token_notice(&token), token))))
}
/// A nightly's own session record: whether the previous session did not finish normally, to be
/// reported once the window is up. This session is cleared only on a controlled return (`on_exit`,
/// or the code after the event loop). Stable keeps no record.
fn previous_nightly_session_was_unclean(nightly: bool) -> bool {
if !nightly {
return false;
}
match nightly_session::begin(nightly_root(), vectorcraft_ui_egui::os_window::version(), None) {
Ok(unclean) => unclean,
Err(e) => {
log::warn!("Nightly session health is unavailable: {e}");
false
}
}
}
/// The first log lines: the version and channel, then a nightly's profile root.
fn log_startup(nightly: bool) {
log::info!("VectorCraft {} ({})", vectorcraft_ui_egui::os_window::version(), channel_name());
if nightly {
log::info!("nightly profile: {}", nightly_root().map(|root| root.display().to_string()).unwrap_or_default());
}
}
/// Windows: the update helper is a copy of this program started with `--finish-update`. Nightly is
/// updated by the Launcher, so it never starts one (`build_flavor` keeps its updater off).
#[cfg(windows)]
fn finish_pending_update(nightly: bool) {
if !nightly
&& let Some(result) = craft::update::self_update::finish(&vectorcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
{
std::process::exit(i32::from(result.is_err()));
}
}
fn main() -> std::process::ExitCode {
// The launch profile first: a nightly build without one is refused here, before the update
// helper, the logger, fonts or any saved state, and `--version` is answered here too.
let Some(arguments) = prepare_launch() else { return std::process::ExitCode::SUCCESS };
let nightly = launch_profile::current().is_nightly();
#[cfg(windows)]
finish_pending_update(nightly);
// Before any thread starts: the pointer must find a cursor theme on Wayland (#2450).
#[cfg(target_os = "linux")]
cursor_theme::apply();
@@ -348,32 +529,21 @@ fn main() -> std::process::ExitCode {
let mut roots_args =
automation_args::AutomationArgs::new(root_env("VECTORCRAFT_AUTOMATION_READ_ROOT"), root_env("VECTORCRAFT_AUTOMATION_WRITE_ROOT"));
let mut presentation = presentation::Overrides::default();
let given = launch_arguments(nightly, &arguments);
let CommandLine { files: command_line_files, in_window_menus, new_instance, safe_mode: safe_mode_flag } =
match read_command_line(std::env::args().skip(1), &mut control, &mut roots_args, &mut presentation) {
match read_command_line(given.into_iter(), &mut control, &mut roots_args, &mut presentation) {
Ok(command_line) => command_line,
Err(code) => return code,
};
let automation_args::AutomationArgs { read_roots, write_roots, .. } = roots_args;
// After the arguments: the flags and `--version` win over a bad environment value.
let control_options = match ControlOptions::resolve(control.options(), &EnvNames::for_app("VECTORCRAFT")) {
Ok(options) => options,
Err(e) => {
eprintln!("vectorcraft: {e}");
return std::process::ExitCode::FAILURE;
}
};
let control_port = control_options.port;
// Read before the window opens: a token file that can't be read keeps the app from starting
// rather than leaving the channel open without one.
let control_token = match control_port.map(|_| control_options.server_token()).transpose() {
Ok(token) => token.map(|token| (control_options.token_notice(&token), token)),
Err(e) => {
eprintln!("vectorcraft: {e}");
return std::process::ExitCode::FAILURE;
}
};
let (control_port, control_token) = control_channel(&control, nightly).unwrap_or_else(|message| {
eprintln!("vectorcraft: {message}");
std::process::exit(1)
});
// Before desktop services, so every start-up warning is recorded (`logging`).
let logger = logging::install();
log_startup(nightly);
// Files opened from the file manager while VectorCraft runs open in its window (#4892). Before
// the log file is attached: a launch that hands its files over leaves the running app's log be.
#[cfg(not(target_os = "macos"))]
@@ -401,13 +571,14 @@ fn main() -> std::process::ExitCode {
if let Some(logger) = logger {
match log_dir().filter(|_| prefs_enabled()) {
Some(dir) => match logger.attach_dir(&dir) {
Ok(path) => log::info!("VectorCraft {}, log file {}", env!("CARGO_PKG_VERSION"), path.display()),
Ok(path) => log::info!("VectorCraft {}, log file {}", vectorcraft_ui_egui::os_window::version(), path.display()),
// Standard error only by now (`attach_dir` gave up on the file); unlike `eprintln!`, never panics.
Err(e) => log::warn!("no log file: {e}"),
},
None => logger.no_file(),
}
}
let previous_nightly_unclean = previous_nightly_session_was_unclean(nightly);
// The report a session left when it was closed while it did not answer (`hang_watch`).
let previous_hang = log_dir().filter(|_| prefs_enabled()).and_then(|dir| hang_watch::take_previous(&dir));
if let Some(report) = &previous_hang {
@@ -591,11 +762,11 @@ fn main() -> std::process::ExitCode {
let run = |options: eframe::NativeOptions, app_creator: eframe::AppCreator<'_>| {
#[cfg(target_os = "linux")]
{
linux_stylus::run_native("VectorCraft", options, app_creator)
linux_stylus::run_native(vectorcraft_ui_egui::os_window::name(), options, app_creator)
}
#[cfg(not(target_os = "linux"))]
{
eframe::run_native("VectorCraft", options, app_creator)
eframe::run_native(vectorcraft_ui_egui::os_window::name(), options, app_creator)
}
};
let outcome = vectorcraft_engine::guard::catch_panic(|| {
@@ -605,8 +776,8 @@ fn main() -> std::process::ExitCode {
let ctx = &cc.egui_ctx;
let winit_window = cc.winit_window().cloned();
let spec = InstallSpec::new(shell_info, Arc::new(SystemWindows))
.app_id(WINDOW_APP_ID)
.placement(Arc::new(Mutex::new(Store::open("vectorcraft"))))
.app_id(vectorcraft_ui_egui::os_window::app_id())
.placement(Arc::new(Mutex::new(placement_store())))
.frame(decision);
let spec = match start_pen(&winit_window) {
Some(pen) => spec.pen(pen),
@@ -621,11 +792,15 @@ fn main() -> std::process::ExitCode {
};
let (files, file_panels) = file_service(wake, folders);
let files = Arc::new(files);
craft::host::Host::builder(AppInfo { id: "vectorcraft", name: "VectorCraft", version: env!("CARGO_PKG_VERSION") })
.i18n(vectorcraft_ui_egui::i18n::shared())
.settings(Arc::new(settings.clone()))
.files(files.clone())
.install(ctx);
craft::host::Host::builder(AppInfo {
id: vectorcraft_ui_egui::os_window::SETTINGS_APP_ID,
name: vectorcraft_ui_egui::os_window::name(),
version: vectorcraft_ui_egui::os_window::version(),
})
.i18n(vectorcraft_ui_egui::i18n::shared())
.settings(Arc::new(settings.clone()))
.files(files.clone())
.install(ctx);
let mut session = Session::new();
// The profiles loaded before come back before the preferences name any of them.
prefs_dir::attach_profile_store(&mut session);
@@ -636,6 +811,9 @@ fn main() -> std::process::ExitCode {
let launch_dir = prefs_dir::prefs_dir().filter(|_| prefs_enabled()).map(|d| d.join("Launch"));
let folder = |name: &str| prefs_dir::prefs_dir().map(|d| d.join(name).to_string_lossy().to_string());
let stopped = safe_mode::begin_launch(launch_dir.as_deref(), safe_mode_flag);
// The launch's loads of the stored plug-ins and the plug-ins folder go on on worker
// threads while the window shows; the frames install them as they finish.
session.load_plugins_in_background(true);
prefs_dir::attach_plugin_store(&mut session);
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
prefs_dir::attach_scripts_dir(&mut session);
@@ -646,9 +824,14 @@ fn main() -> std::process::ExitCode {
prefs_dir::attach_script_data(&mut session);
let mut app = VectorcraftApp::new(session, services(winit_window.clone()));
app.adopt_context(&cc.egui_ctx);
app.set_startup_update_check(true);
// A nightly is updated by the Launcher: it never checks for a stable release, which
// would install this program's own updater over the nightly build.
app.set_startup_update_check(!nightly);
load_prefs(&mut app, &settings);
safe_mode::after_start(&mut app, stopped);
// Loads started later (a preference change, the end of Safe Mode) are waited for,
// after the launch's own.
app.session.load_plugins_in_background(false);
// The saved PDF presets live in their own folder (also read by vectorcraft-cli),
// which takes over from the copy the preferences file used to hold.
prefs_dir::attach_pdf_preset_store(&mut app.session);
@@ -741,6 +924,17 @@ fn main() -> std::process::ExitCode {
if previous_hang.is_some() && app.ui.status.is_empty() {
vectorcraft_ui_egui::troubleshooting::last_session_stopped(&mut app);
}
// The previous nightly session did not finish normally: say so once, in the window
// that is now up, and only then let a clean exit clear the record.
if previous_nightly_unclean {
// A graphics, plug-in or hang message may be up already: keep it, as above.
if app.ui.status.is_empty() {
app.status(
"The previous VectorCraft Nightly session did not finish normally. Nothing has been sent anywhere; Help › About has this build's version for a bug report",
);
}
nightly_session::mark_notice_shown();
}
let mut control_server = None;
if let (Some(port), Some((notice, token))) = (control_port, control_token) {
match server::listen(port, token, craft::ui::runtime::windows::WindowHost::of(&cc.egui_ctx)) {
@@ -803,7 +997,13 @@ fn main() -> std::process::ExitCode {
)
});
// The window is gone: later launches start their own app, including the one a graphics
// failure starts again below.
// failure starts again below. A nightly's session record is finished here, by the controlled
// return, before a successor can take the profile; on macOS the window's own `on_exit` already
// did it (a Dock quit ends the process inside AppKit), so this is then a no-op. A run that
// reports a startup error has still returned in a controlled way (that error is logged and
// exits FAILURE below), so only a caught panic keeps the record for the next launch to report;
// it then also frees the lease for the successor this run may still start.
nightly_session::finish_after(outcome.is_ok());
#[cfg(not(target_os = "macos"))]
single_instance::resign();
// The process ends normally from here: this launch didn't stop while a plug-in was loading.
+297
View File
@@ -0,0 +1,297 @@
//! App-private Nightly session health, not telemetry and not a Launcher protocol.
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
use std::fs::{File, OpenOptions};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, PoisonError};
const RECORD: &str = "nightly-session.json";
const LEASE: &str = "nightly-session.lock";
const MAX_METADATA_BYTES: usize = 256;
static SESSION: Mutex<Option<Session>> = Mutex::new(None);
/// Set once a window has posted the interruption notice; until then the record must survive.
static NOTICE_SHOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub struct Session {
_lease: File,
path: PathBuf,
own_record: Vec<u8>,
previous_unclean: bool,
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
/// Replace `path` with `bytes` without ever following a link at the destination: the temporary file
/// is created fresh in the same folder and renamed over the name, and a rename replaces the link
/// itself, never its target. A destination that is not a regular file is refused.
fn atomic_write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
// A destination that is a folder or a link is refused before anything is written.
regular_or_missing(path)?;
let dir = path.parent().ok_or_else(|| io::Error::other("Nightly session state has no folder"))?;
std::fs::create_dir_all(dir)?;
let name = path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();
let temporary = dir.join(format!(".{name}.{}.tmp", std::process::id()));
let _ = std::fs::remove_file(&temporary);
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
let written = options.open(&temporary).and_then(|mut file| {
use std::io::Write as _;
file.write_all(bytes)?;
file.sync_all()?;
std::fs::rename(&temporary, path)
});
if written.is_err() {
// Best effort: the temporary file is all there is to clean up.
let _ = std::fs::remove_file(&temporary);
}
if written.is_ok()
&& let Ok(handle) = File::open(dir)
{
// The rename is durable once its folder is.
let _ = handle.sync_all();
}
written
}
impl Session {
/// This launch's record: `None` for a stable build or when another window of the same profile
/// owns it. The root must already be the validated private Nightly profile.
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
let Some(root) = root else { return Ok(None) };
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
}
let lease_path = root.join(LEASE);
regular_or_missing(&lease_path)?;
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
match lease.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
Err(std::fs::TryLockError::Error(error)) => return Err(error),
}
let path = root.join(RECORD);
let previous_unclean = regular_or_missing(&path)?;
let own_record = serde_json::to_vec(&serde_json::json!({
"schema_version": 1,
"channel": "nightly-v1",
"version": version,
"commit": commit.filter(|value| !value.is_empty()),
}))?;
atomic_write_no_follow(&path, &own_record)?;
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
}
pub fn previous_unclean(&self) -> bool {
self.previous_unclean
}
/// Controlled return. If an earlier session's interruption was detected but no window showed it
/// yet (a renderer failure before the app callback, or the hand-off to a second window), the
/// record is left for the next owner to report; otherwise this is [`Self::complete`].
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
if self.previous_unclean && !unclean_notice_shown {
return Ok(());
}
self.complete()
}
/// Controlled event-loop completion, including a handled startup error. Clear before a successor
/// can take the profile. An unwind, abort, forced exit or killed process never calls this.
pub fn complete(self) -> io::Result<()> {
if !regular_or_missing(&self.path)? {
return Ok(());
}
let mut current = Vec::new();
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
if current != self.own_record {
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
}
std::fs::remove_file(&self.path)
}
}
/// Starts this launch's record, keeping it until [`finish_once`]. A profile another window already
/// owns gets no record (`Ok(false)` and no notice); a failure to record is reported, never fatal.
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> Result<bool, String> {
let session = Session::begin(root, version, commit).map_err(|e| e.to_string())?;
let previous_unclean = session.as_ref().is_some_and(Session::previous_unclean);
*SESSION.lock().unwrap_or_else(PoisonError::into_inner) = session;
Ok(previous_unclean)
}
/// A window showed the interruption notice: a controlled return now clears the record.
pub fn mark_notice_shown() {
NOTICE_SHOWN.store(true, std::sync::atomic::Ordering::Relaxed);
}
/// The controlled return, by whichever path comes first (the window's `on_exit`, which every quit
/// reaches, or the code after the event loop). Later calls do nothing.
pub fn finish_once() {
let shown = NOTICE_SHOWN.load(std::sync::atomic::Ordering::Relaxed);
let watch = SESSION.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(watch) = watch
&& let Err(error) = watch.finish(shown)
{
log::warn!("Nightly session state was left intact: {error}");
}
}
/// The end of a launch: a controlled return clears the record ([`finish_once`]); an abnormal one
/// (a caught panic) keeps it for the next launch to report and only frees the lease, so the
/// successor a graphics restart starts can take the profile.
pub fn finish_after(clean: bool) {
if clean { finish_once() } else { release() }
}
/// An abnormal end: the record stays, the lease is dropped. Later calls do nothing.
fn release() {
drop(SESSION.lock().unwrap_or_else(PoisonError::into_inner).take());
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
loop {
let path =
std::env::temp_dir().join(format!("vectorcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&path) {
Ok(()) => return Self(path),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
}
}
}
impl Drop for Fixture {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).unwrap();
}
}
#[test]
fn stable_has_no_session_side_effects() {
let fixture = Fixture::new();
assert!(Session::begin(None, "0.24.1", None).unwrap().is_none());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
}
#[test]
fn a_busy_secondary_reports_nothing_and_keeps_the_owner_record() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap().unwrap();
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "a busy secondary must not replace the owner's record");
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
assert!(!first.previous_unclean());
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
assert!(!unfinished.previous_unclean());
drop(unfinished); // Unwind or abnormal ownership release, not a controlled completion.
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
let fixture = Fixture::new();
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
// The window failed before the app callback: no notice was shown.
let failed = Session::begin(Some(&fixture.0), "failed", None).unwrap().unwrap();
assert!(failed.previous_unclean());
failed.finish(false).unwrap();
let retry = Session::begin(Some(&fixture.0), "retry", None).unwrap().unwrap();
assert!(retry.previous_unclean());
retry.finish(true).unwrap();
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
assert!(!clean.previous_unclean());
clean.finish(false).unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn an_abnormal_end_keeps_the_record_but_frees_the_lease() {
let fixture = Fixture::new();
assert!(!begin(Some(&fixture.0), "nightly", Some("panicked")).unwrap());
finish_after(false);
// A second end is a no-op, and the record stays for the next launch to report.
finish_after(false);
assert!(fixture.0.join(RECORD).exists(), "a caught panic leaves its record");
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
assert!(successor.previous_unclean(), "the successor reports the interruption");
successor.finish(true).unwrap();
assert!(!fixture.0.join(RECORD).exists());
// A controlled return still clears the record it recorded.
assert!(!begin(Some(&fixture.0), "clean", None).unwrap());
finish_after(true);
assert!(!fixture.0.join(RECORD).exists(), "a controlled return clears its record");
}
#[test]
fn cleanup_never_removes_an_unknown_changed_record() {
let fixture = Fixture::new();
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
assert!(watch.complete().is_err());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
}
#[test]
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
let fixture = Fixture::new();
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
assert!(data["commit"].is_null(), "missing provenance must not be invented");
watch.complete().unwrap();
}
#[cfg(unix)]
#[test]
fn reserved_state_aliases_do_not_modify_external_files() {
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
for name in [LEASE, RECORD] {
let alias = fixture.0.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err(), "{name}");
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
std::fs::remove_file(alias).unwrap();
}
}
}
+82
View File
@@ -0,0 +1,82 @@
//! Set the immutable nightly Windows identity (the taskbar group and jump-list id) before any native
//! window or COM service. Stable deliberately leaves its implicit shortcut identity unchanged, so the
//! MSI's shortcuts keep matching it.
use std::sync::OnceLock;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum IdentityError {
Configuration(String),
}
impl std::fmt::Display for IdentityError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Configuration(message) => f.write_str(message),
}
}
}
impl std::error::Error for IdentityError {}
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
// winsafe arrives with the wgpu renderer, which every desktop package builds with.
configure(nightly && cfg!(windows) && cfg!(feature = "wgpu"), app_id, |id| {
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
RESULT
.get_or_init(|| {
#[cfg(all(windows, feature = "wgpu"))]
{
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
if actual != id {
return Err("the native Windows identity did not match the selected nightly channel".to_string());
}
Ok(())
}
#[cfg(not(all(windows, feature = "wgpu")))]
{
let _ = id;
Ok(())
}
})
.clone()
})
.map_err(IdentityError::Configuration)
}
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
if explicit_nightly { set(app_id) } else { Ok(()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stable_does_not_call_the_explicit_identity_api() {
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
}
#[test]
fn nightly_applies_the_supplied_identity_once() {
let calls = std::cell::Cell::new(0);
configure(true, "nightly-id", |id| {
assert_eq!(id, "nightly-id");
calls.set(calls.get() + 1);
Ok(())
})
.unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
let started = std::cell::Cell::new(false);
let result = configure(true, "nightly-id", |_| Err("native identity refused".to_string())).map(|()| started.set(true));
assert_eq!(result.unwrap_err(), "native identity refused");
assert!(!started.get());
}
}
+85 -23
View File
@@ -1,6 +1,9 @@
//! Native profile paths. Isolated profiles never migrate preferences from a user's old profile.
//!
//! In order:
//! 0. The profile root a nightly launch selected ([`install_data_root`]): the Launcher's private
//! folder, which every one of the app's settings, logs, recovery copies, plug-ins, caches and
//! single-instance records then follows, with no legacy migration.
//! 1. `VECTORCRAFT_CONFIG_DIR`, when set (tests, agents, custom setups).
//! 2. **Portable mode** (#1366), as in PhotoCraft: a marker file ([`PORTABLE_MARKERS`]) in the
//! install folder puts the settings in `VectorCraftData` beside it, so a portable copy leaves
@@ -24,14 +27,45 @@ pub const PORTABLE_MARKERS: [&str; 2] = ["portable.txt", "VectorCraft.portable"]
/// The settings folder created in the install folder in portable mode.
pub const PORTABLE_DATA_DIR: &str = "VectorCraftData";
/// The settings folder of VectorCraft, or of DrawCraft (`legacy`).
pub fn prefs_dir(legacy: bool) -> Option<PathBuf> {
prefs_dir_with(std::env::consts::OS, legacy, |key| std::env::var_os(key), portable_dir)
/// The profile root this process was launched with, if any: a nightly launch's private folder.
static DATA_ROOT: OnceLock<PathBuf> = OnceLock::new();
/// Makes `root` this process's settings folder and everything under it, once, before anything reads
/// a path. The desktop calls it from `prepare_launch` with the root it validated; the command line
/// tool never does, so it keeps resolving the user's own folder.
// The desktop installs it from `prepare_launch`; `vectorcraft-cli` includes this file and never does.
#[allow(dead_code)]
pub(crate) fn install_data_root(root: PathBuf) -> Result<(), String> {
if !root.is_absolute() {
return Err("the data root must be absolute".to_string());
}
DATA_ROOT.set(root).map_err(|_| "the data root was already installed".to_string())
}
/// `portable` is the portable settings folder, if any: only asked for when no override is set and
/// preferences are in use.
fn prefs_dir_with(os: &str, legacy: bool, env: impl Fn(&str) -> Option<OsString>, portable: impl FnOnce() -> Option<PathBuf>) -> Option<PathBuf> {
/// The installed profile root, if this launch has one.
pub(crate) fn data_root() -> Option<&'static Path> {
DATA_ROOT.get().map(PathBuf::as_path)
}
/// The settings folder of VectorCraft, or of DrawCraft (`legacy`).
pub fn prefs_dir(legacy: bool) -> Option<PathBuf> {
prefs_dir_with(std::env::consts::OS, legacy, |key| std::env::var_os(key), portable_dir, data_root())
}
/// `portable` is the portable settings folder, if any: only asked for when neither the launch's
/// profile nor an override is set and preferences are in use.
fn prefs_dir_with(
os: &str,
legacy: bool,
env: impl Fn(&str) -> Option<OsString>,
portable: impl FnOnce() -> Option<PathBuf>,
root: Option<&Path>,
) -> Option<PathBuf> {
// A nightly launch's private profile wins over everything, and a run of DrawCraft's legacy
// folder is never read into it.
if let Some(root) = root {
return (!legacy).then(|| root.to_path_buf());
}
if let Some(root) = env("VECTORCRAFT_CONFIG_DIR") {
// Never fall back to DrawCraft's real profile when the isolated file does not exist.
return (!legacy && !root.is_empty()).then(|| PathBuf::from(root));
@@ -125,8 +159,9 @@ fn portable_dir_in(install_dir: &Path, previous: Option<&Path>) -> Result<Option
Ok(Some(data))
}
/// Create `dir` and prove a file can be written in it (a folder can exist yet be read-only).
fn ensure_writable(dir: &Path) -> std::io::Result<()> {
/// Create `dir` and prove a file can be written in it (a folder can exist yet be read-only). The
/// nightly profile validator wires this same probe in ([`crate::profile_root`]).
pub(crate) fn ensure_writable(dir: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
let probe = dir.join(format!(".write-test-{}", std::process::id()));
std::fs::write(&probe, b"")?;
@@ -230,26 +265,26 @@ mod tests {
let env = |key: &str| {
if key == "VECTORCRAFT_CONFIG_DIR" { Some("/isolated".into()) } else { environment(key) }
};
assert_eq!(prefs_dir_with(os, false, env, installed), Some("/isolated".into()));
assert_eq!(prefs_dir_with(os, true, env, installed), None);
assert_eq!(prefs_dir_with(os, false, env, installed, None), Some("/isolated".into()));
assert_eq!(prefs_dir_with(os, true, env, installed, None), None);
}
}
#[test]
fn empty_override_does_not_fall_back_to_user_files() {
let env = |key: &str| if key == "VECTORCRAFT_CONFIG_DIR" { Some(OsString::new()) } else { environment(key) };
assert_eq!(prefs_dir_with("macos", false, env, installed), None);
assert_eq!(prefs_dir_with("macos", true, env, installed), None);
assert_eq!(prefs_dir_with("macos", false, env, installed, None), None);
assert_eq!(prefs_dir_with("macos", true, env, installed, None), None);
}
#[test]
fn unset_override_keeps_platform_paths_and_legacy_migration() {
assert_eq!(prefs_dir_with("macos", false, environment, installed), Some("/user/Library/Application Support/VectorCraft".into()));
assert_eq!(prefs_dir_with("macos", true, environment, installed), Some("/user/Library/Application Support/DrawCraft".into()));
assert_eq!(prefs_dir_with("windows", false, environment, installed), Some("/roaming/VectorCraft".into()));
assert_eq!(prefs_dir_with("linux", false, environment, installed), Some("/xdg-config/vectorcraft".into()));
assert_eq!(prefs_dir_with("macos", false, environment, installed, None), Some("/user/Library/Application Support/VectorCraft".into()));
assert_eq!(prefs_dir_with("macos", true, environment, installed, None), Some("/user/Library/Application Support/DrawCraft".into()));
assert_eq!(prefs_dir_with("windows", false, environment, installed, None), Some("/roaming/VectorCraft".into()));
assert_eq!(prefs_dir_with("linux", false, environment, installed, None), Some("/xdg-config/vectorcraft".into()));
assert_eq!(
prefs_dir_with("linux", true, |key| if key == "HOME" { environment(key) } else { None }, installed),
prefs_dir_with("linux", true, |key| if key == "HOME" { environment(key) } else { None }, installed, None),
Some("/user/.config/drawcraft".into())
);
}
@@ -258,9 +293,9 @@ mod tests {
fn portable_mode_keeps_the_settings_beside_the_executable_and_skips_the_drawcraft_profile() {
let portable = || Some(PathBuf::from("/usb/VectorCraft/VectorCraftData"));
for os in ["macos", "windows", "linux"] {
assert_eq!(prefs_dir_with(os, false, environment, portable), Some("/usb/VectorCraft/VectorCraftData".into()), "{os}");
assert_eq!(prefs_dir_with(os, false, environment, portable, None), Some("/usb/VectorCraft/VectorCraftData".into()), "{os}");
// A portable copy is self-contained: the one-time read of DrawCraft's old settings is skipped.
assert_eq!(prefs_dir_with(os, true, environment, portable), None, "{os}");
assert_eq!(prefs_dir_with(os, true, environment, portable, None), None, "{os}");
}
}
@@ -268,16 +303,16 @@ mod tests {
fn the_config_dir_override_wins_over_portable_mode_without_probing_it() {
let env = |key: &str| if key == "VECTORCRAFT_CONFIG_DIR" { Some("/isolated".into()) } else { environment(key) };
let portable = || -> Option<PathBuf> { panic!("the portable folder is not looked for under VECTORCRAFT_CONFIG_DIR") };
assert_eq!(prefs_dir_with("windows", false, env, portable), Some("/isolated".into()));
assert_eq!(prefs_dir_with("windows", true, env, portable), None);
assert_eq!(prefs_dir_with("windows", false, env, portable, None), Some("/isolated".into()));
assert_eq!(prefs_dir_with("windows", true, env, portable, None), None);
}
#[test]
fn a_run_without_preferences_never_looks_for_the_portable_folder() {
let env = |key: &str| if key == "VECTORCRAFT_NO_PREFS" { Some("1".into()) } else { environment(key) };
let portable = || -> Option<PathBuf> { panic!("the portable folder is not looked for under VECTORCRAFT_NO_PREFS") };
assert_eq!(prefs_dir_with("windows", false, env, portable), Some("/roaming/VectorCraft".into()));
assert_eq!(prefs_dir_with("windows", true, env, portable), Some("/roaming/DrawCraft".into()));
assert_eq!(prefs_dir_with("windows", false, env, portable, None), Some("/roaming/VectorCraft".into()));
assert_eq!(prefs_dir_with("windows", true, env, portable, None), Some("/roaming/DrawCraft".into()));
}
#[test]
@@ -407,4 +442,31 @@ mod tests {
let _ = std::fs::remove_dir_all(&from);
let _ = std::fs::remove_dir_all(&to);
}
#[test]
fn the_launch_profile_root_wins_over_every_other_rule_without_touching_the_disk() {
let root = Path::new("/launcher/profiles/vectorcraft");
let portable = || -> Option<PathBuf> { panic!("the portable folder is not looked for under a profile root") };
for os in ["macos", "windows", "linux"] {
for override_dir in [None, Some("/isolated")] {
let env = |key: &str| if key == "VECTORCRAFT_CONFIG_DIR" { override_dir.map(OsString::from) } else { environment(key) };
assert_eq!(prefs_dir_with(os, false, env, portable, Some(root)), Some(root.to_path_buf()), "{os}");
// A nightly profile never takes DrawCraft's old settings over.
assert_eq!(prefs_dir_with(os, true, env, portable, Some(root)), None, "{os}");
}
}
}
/// Installs the process-wide root: the one test that may, since a `OnceLock` is set once per
/// process (nextest gives every test its own).
#[test]
fn the_installed_root_is_used_once_and_must_be_absolute() {
let dir = temp("installed-root");
assert!(install_data_root(PathBuf::from("relative/root")).is_err(), "a relative root is refused");
install_data_root(dir.to_path_buf()).unwrap();
assert_eq!(data_root(), Some(&*dir));
assert_eq!(prefs_dir(false), Some(dir.to_path_buf()));
assert!(install_data_root(PathBuf::from("/elsewhere")).is_err(), "a second install is refused");
assert_eq!(data_root(), Some(&*dir), "the first root stays");
}
}
+568
View File
@@ -0,0 +1,568 @@
//! App-owned nightly profile fences: a profile every one of VectorCraft's data paths is redirected
//! into ([`crate::prefs_dir::profile::install_data_root`]), and that never overlaps stable's folders, a portable
//! copy or an installation.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use crate::prefs_dir::profile::PORTABLE_DATA_DIR;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
other => Err(format!("nightly-v1 is not defined for this operating system ({other})")),
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or_else(|| "the profile root has no existing ancestor".to_string())?.to_os_string());
parent = parent.parent().ok_or_else(|| "the profile root has no existing ancestor".to_string())?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
/// A stable entry point may be a dangling link once its target is uninstalled. Its own name is still
/// the fence, so only the folder it lives in is resolved: a link that cannot be resolved would refuse
/// every launch, a valid private profile included.
fn canonical_future_entry(path: &Path) -> Result<PathBuf, String> {
let parent = path.parent().ok_or_else(|| "an entry point has no folder".to_string())?;
let name = path.file_name().ok_or_else(|| "an entry point has no name".to_string())?;
Ok(canonical_future(parent)?.join(name))
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str().to_string_lossy().into_owned();
if platform.ignores_case() { value.to_lowercase() } else { value }
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or_else(|| "cannot establish the installation boundary".to_string())?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
Ok(parent.to_path_buf())
}
/// Every folder a stable VectorCraft keeps user state in, on `platform`: the settings folder each
/// platform convention and the portable layout use, the eframe window state, the logs, the recovery
/// copies, the plug-ins, the caches, the install folders and the entry points. A nightly profile that
/// overlapped any of them would read, rewrite or prune stable's own state.
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
// The settings folder (`profile.rs`) and the eframe window state, which eframe puts under
// `%APPDATA%\ai.storyteller.vectorcraft\data` (the window id).
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("VectorCraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.push(required_base(env, "APPDATA")?.join("ai.storyteller.vectorcraft"));
// The MSI's default per-user and per-machine folders (install-policy.wxi). A custom
// install folder is not known here; the executable's own folder is fenced below.
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("VectorCraft"));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("VectorCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("vectorcraft")))
.collect::<Result<Vec<_>, _>>()?;
// The eframe window state, under the lowercased window id.
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join("ai.storyteller.vectorcraft"));
roots.push(required_base(env, "HOME")?.join(".config").join("VectorCraft"));
// The same folders at their HOME defaults: an XDG override moves this launch's own paths,
// not stable's, which stays where a launch without the override finds it.
for (directory, app) in
[(".config", "vectorcraft"), (".local/share", "vectorcraft"), (".cache", "vectorcraft"), (".local/state", "vectorcraft")]
{
roots.push(required_base(env, "HOME")?.join(directory).join(app));
}
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.vectorcraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/VectorCraft"),
library.join("Application Support/ai.storyteller.vectorcraft"),
library.join("Caches/VectorCraft"),
library.join("Caches/ai.storyteller.vectorcraft"),
library.join("Preferences/VectorCraft"),
library.join("Preferences/ai.storyteller.vectorcraft.plist"),
library.join("Saved Application State/ai.storyteller.vectorcraft.savedState"),
home.join("Applications/VectorCraft.app"),
PathBuf::from("/Applications/VectorCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
let mut fences = roots.into_iter().map(|p| canonical_future(&p)).collect::<Result<Vec<_>, _>>()?;
if platform == Platform::Linux {
for entry in ["/usr/bin/vectorcraft", "/usr/local/bin/vectorcraft", "/opt/vectorcraft"] {
fences.push(canonical_future_entry(Path::new(entry))?);
}
}
Ok(fences)
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
Ok(child)
}
/// Every existing entry directly in the profile (settings, logs, the user's libraries and so on) must
/// resolve inside it, so a link there cannot point Nightly's writes at another app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
Ok(())
}
/// Recognise the shared portable data namespace in both the supplied and the resolved path. Up to
/// the chosen folder itself, a marker only counts beside a VectorCraft executable, so an unrelated
/// `portable.txt` higher up (in a user folder or at a drive root) does not refuse the profile.
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
path.ancestors().enumerate().any(|(depth, ancestor)| {
crate::prefs_dir::profile::PORTABLE_MARKERS.iter().any(|marker| ancestor.join(marker).is_file())
&& (depth == 0 || ["vectorcraft.exe", "vectorcraft"].iter().any(|exe| ancestor.join(exe).is_file()))
}) || path.components().any(|component| match component {
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
Component::Normal(name) => name == PORTABLE_DATA_DIR,
_ => false,
})
}
/// The writable hook is the app's own exclusive probe ([`crate::prefs_dir::profile::ensure_writable`]). Keeping
/// it injected lets the boundary tests exercise the real policy without starting the app.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
if env("VECTORCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) {
return Err("nightly-v1 cannot be combined with VECTORCRAFT_CONFIG_DIR".to_string());
}
// The app turns preferences off whenever the variable is present, empty value included.
if env("VECTORCRAFT_NO_PREFS").is_some() {
// A run without preferences keeps nothing: its own profile would stay unused and the app
// would log to standard error only, so it is never a nightly launch.
return Err("nightly-v1 cannot inherit VECTORCRAFT_NO_PREFS".to_string());
}
let nightly_flatpak = vectorcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID;
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|value| !value.is_empty())
&& id.to_string_lossy().as_ref() != nightly_flatpak
{
// `packaging/linux/flatpak-bundle.sh` builds VectorCraft Nightly as its own Flatpak
// (`ai.storyteller.vectorcraft.nightly`), whose sandbox is already a private home. Any other
// instance, the stable app's included, would put this profile inside another app's tree.
return Err(format!("nightly-v1 can only run inside its own Flatpak instance ({nightly_flatpak}), not {}", id.to_string_lossy()));
}
let chosen = canonical_future(root)?;
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
return Err("the nightly root must not use a portable VectorCraft installation or its VectorCraftData settings folder".to_string());
}
let exe = absolute(exe.ok_or_else(|| "cannot establish the installation boundary".to_string())?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".to_string());
}
// Data Recovery can read, adopt, overwrite and sweep entries: never let its alias leave the
// private profile.
private_subdirectory(&chosen, "Data Recovery", "recovery folder")?;
entries_stay_inside(&chosen)?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".to_string());
}
private_subdirectory(&confirmed, "Data Recovery", "recovery folder")?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
/// An owned fixture tree: a home, a roaming/local app-data pair and an install folder, so the
/// fence can be checked for every platform on any host.
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("vectorcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/vectorcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
self.check_with(platform, root, |_| Ok(()))
}
fn check_with(&self, platform: Platform, root: &Path, writable: impl FnOnce(&Path) -> std::io::Result<()>) -> Result<PathBuf, String> {
validate_for(platform, root, |key| self.get(key), Some(&self.exe), writable)
}
}
impl Drop for Fixture {
fn drop(&mut self) {
// Only the directory this fixture created is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
const PLATFORMS: [Platform; 3] = [Platform::Windows, Platform::Linux, Platform::Mac];
#[test]
fn a_private_profile_is_accepted_on_every_platform() {
let fixture = Fixture::new();
for platform in PLATFORMS {
let root = fixture.root.join(format!("nightly profiles/{platform:?}/vectorcraft"));
let resolved = fixture.check(platform, &root).unwrap();
assert!(resolved.is_dir(), "{platform:?}");
assert_eq!(resolved, std::fs::canonicalize(root).unwrap(), "{platform:?}");
std::fs::remove_dir_all(fixture.root.join("nightly profiles")).unwrap();
}
}
#[test]
fn stable_settings_folders_are_refused_on_every_platform() {
let fixture = Fixture::new();
let stable = [
(Platform::Windows, fixture.get("APPDATA").map(|v| PathBuf::from(v).join("VectorCraft"))),
(Platform::Windows, fixture.get("APPDATA").map(|v| PathBuf::from(v).join("ai.storyteller.vectorcraft"))),
(Platform::Windows, fixture.get("LOCALAPPDATA").map(|v| PathBuf::from(v).join("VectorCraft"))),
(Platform::Windows, fixture.get("LOCALAPPDATA").map(|v| PathBuf::from(v).join("Programs/ArtCraft/VectorCraft"))),
(Platform::Linux, Some(fixture.home().join(".config/vectorcraft"))),
(Platform::Linux, Some(fixture.home().join(".local/share/vectorcraft"))),
(Platform::Linux, Some(fixture.home().join(".local/share/ai.storyteller.vectorcraft"))),
(Platform::Linux, Some(fixture.home().join(".cache/vectorcraft"))),
(Platform::Linux, Some(fixture.home().join(".var/app/ai.storyteller.vectorcraft"))),
(Platform::Mac, Some(fixture.home().join("Library/Application Support/VectorCraft"))),
(Platform::Mac, Some(fixture.home().join("Library/Application Support/ai.storyteller.vectorcraft"))),
(Platform::Mac, Some(fixture.home().join("Library/Preferences/ai.storyteller.vectorcraft.plist"))),
];
for (platform, stable) in stable {
let stable = stable.unwrap();
for candidate in [stable.clone(), stable.join("nested nightly")] {
let probed = Cell::new(false);
let result = fixture.check_with(platform, &candidate, |_| {
probed.set(true);
Ok(())
});
assert!(result.is_err(), "{platform:?} accepted {candidate:?}");
assert!(!probed.get(), "a refused root is rejected before the writable probe");
}
}
}
#[test]
fn the_install_folder_and_the_entry_points_are_refused() {
let fixture = Fixture::new();
for platform in PLATFORMS {
let install = fixture.exe.parent().unwrap();
assert!(fixture.check(platform, install).is_err(), "{platform:?}: the install folder");
assert!(fixture.check(platform, &install.join("NightlyData")).is_err(), "{platform:?}: inside the install");
}
}
#[test]
fn an_inherited_config_or_no_prefs_override_is_refused() {
let fixture = Fixture::new();
let root = fixture.root.join("nightly");
for (key, value) in [
("VECTORCRAFT_CONFIG_DIR", "/elsewhere"),
("VECTORCRAFT_NO_PREFS", "1"),
// The app turns preferences off on presence, so an empty value is a run too.
("VECTORCRAFT_NO_PREFS", ""),
("FLATPAK_ID", "ai.storyteller.vectorcraft"),
] {
for platform in PLATFORMS {
let result = validate_for(
platform,
&root,
|name| if name == key { Some(value.into()) } else { fixture.get(name) },
Some(&fixture.exe),
|_| Ok(()),
);
let refused = result.is_err();
// A Flatpak instance only keeps the stable app's sockets on native Unix packages.
assert_eq!(refused, !(key == "FLATPAK_ID" && platform == Platform::Windows), "{key} on {platform:?}");
if refused {
assert!(!root.exists(), "a refused launch creates nothing ({key} on {platform:?})");
} else if root.exists() {
// The accepted case validated the root, which creates it: start the next one clean.
std::fs::remove_dir_all(&root).expect("remove the accepted launch's root");
}
}
}
}
#[test]
fn only_the_nightly_s_own_flatpak_instance_may_carry_a_profile() {
let fixture = Fixture::new();
let root = fixture.root.join("flatpak profile");
for (id, accepted) in
[(vectorcraft_ui_egui::os_window::NIGHTLY_PACKAGE_ID, true), ("ai.storyteller.vectorcraft", false), ("io.other.App", false)]
{
let result = validate_for(
Platform::Linux,
&root,
|name| if name == "FLATPAK_ID" { Some(id.into()) } else { fixture.get(name) },
Some(&fixture.exe),
|_| Ok(()),
);
assert_eq!(result.is_ok(), accepted, "{id}");
let _ = std::fs::remove_dir_all(&root);
}
}
#[test]
fn a_portable_copy_and_its_data_folder_are_refused() {
let fixture = Fixture::new();
let portable = fixture.root.join("portable copy");
let data = portable.join(crate::prefs_dir::profile::PORTABLE_DATA_DIR);
std::fs::create_dir_all(&data).unwrap();
std::fs::write(portable.join("portable.txt"), b"owned portable fixture").unwrap();
std::fs::write(data.join("config.toml"), b"stable settings must not change").unwrap();
for platform in PLATFORMS {
for candidate in [&data, &data.join("nested nightly")] {
let probed = Cell::new(false);
let result = fixture.check_with(platform, candidate, |_| {
probed.set(true);
Ok(())
});
assert!(result.is_err(), "{platform:?} accepted {candidate:?}");
assert!(!probed.get());
assert!(!data.join("nested nightly").exists());
assert_eq!(std::fs::read(data.join("config.toml")).unwrap(), b"stable settings must not change");
}
}
// A merely similar name is not the portable settings folder.
let similar = fixture.root.join("VectorCraftData-backup-name/nightly");
assert!(fixture.check(Platform::Linux, &similar).is_ok());
}
#[cfg(unix)]
#[test]
fn a_link_inside_the_profile_cannot_redirect_recovery_or_a_library() {
let fixture = Fixture::new();
let root = fixture.root.join("nightly");
std::fs::create_dir_all(&root).unwrap();
let external = fixture.root.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
for name in ["Data Recovery", "Swatches"] {
let alias = root.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(fixture.check(Platform::Linux, &root).is_err(), "{name} alias");
std::fs::remove_file(&alias).unwrap();
}
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
}
#[cfg(unix)]
#[test]
fn a_dangling_link_or_a_linked_ancestor_is_refused() {
let fixture = Fixture::new();
let elsewhere = fixture.root.join("elsewhere");
std::fs::create_dir_all(&elsewhere).unwrap();
let linked = fixture.root.join("nightly");
std::os::unix::fs::symlink(&elsewhere, &linked).unwrap();
// Canonical resolution keeps a link's target: a profile reached through one is fine, but it
// is judged (and named) as its target, so nothing is written under the link.
let resolved = fixture.check(Platform::Linux, &linked).unwrap();
assert_eq!(resolved, std::fs::canonicalize(&elsewhere).unwrap());
std::fs::remove_file(&linked).unwrap();
let dangling = fixture.root.join("dangling/nightly");
std::fs::create_dir_all(dangling.parent().unwrap()).unwrap();
std::os::unix::fs::symlink(fixture.root.join("missing"), dangling.parent().unwrap().join("nightly")).unwrap();
assert!(fixture.check(Platform::Linux, &dangling).is_err());
}
#[test]
fn a_home_settings_folder_is_fenced_even_when_the_xdg_override_moves_elsewhere() {
let fixture = Fixture::new();
let xdg = fixture.root.join("override");
std::fs::create_dir_all(&xdg).unwrap();
let config = fixture.home().join(".config/vectorcraft");
let data = fixture.home().join(".local/share/vectorcraft");
for stable in [config.clone(), data.clone()] {
for candidate in [stable.clone(), stable.join("nested nightly")] {
let result = validate_for(
Platform::Linux,
&candidate,
|name| match name {
"XDG_CONFIG_HOME" | "XDG_DATA_HOME" => Some(xdg.clone().into_os_string()),
_ => fixture.get(name),
},
Some(&fixture.exe),
|_| Ok(()),
);
assert!(result.is_err(), "accepted {candidate:?} with the XDG folders moved to {xdg:?}");
}
}
assert!(!config.exists() && !data.exists(), "a refused root creates nothing");
}
#[cfg(unix)]
#[test]
fn a_dangling_entry_point_keeps_its_fence_instead_of_refusing_every_launch() {
let fixture = Fixture::new();
let bin = fixture.root.join("entry/bin");
std::fs::create_dir_all(&bin).unwrap();
let entry = bin.join("vectorcraft");
std::os::unix::fs::symlink(fixture.root.join("uninstalled target"), &entry).unwrap();
// The shared resolver refuses the dangling link, as a profile root must be.
assert!(canonical_future(&entry).is_err());
assert_eq!(canonical_future_entry(&entry).unwrap(), std::fs::canonicalize(&bin).unwrap().join("vectorcraft"));
}
#[test]
fn an_unwritable_profile_is_refused_after_the_probe_and_never_used() {
let fixture = Fixture::new();
let root = fixture.root.join("nightly");
let result = fixture.check_with(Platform::Linux, &root, |_| Err(std::io::Error::other("read-only")));
assert!(result.unwrap_err().contains("not writable"));
}
#[test]
fn the_platform_case_rules_are_the_file_systems_ones() {
let fixture = Fixture::new();
let upper = fixture.root.join("NIGHTLY");
assert!(fixture.check(Platform::Linux, &upper).is_ok());
let stable_mac = fixture.home().join("library/application support/vectorcraft");
assert!(fixture.check(Platform::Mac, &stable_mac).is_err(), "macOS compares folders case-insensitively");
}
}
+3 -2
View File
@@ -144,10 +144,11 @@ pub fn launch_with_plug_ins(files: &[String]) -> io::Result<()> {
}
/// The command [`launch_with_plug_ins`] runs: `exe -- files…`, so a file whose name starts with '-'
/// stays a file.
/// stays a file. A nightly launch hands its profile on first (`launch_profile::child_args`), or the
/// child would refuse to start without one.
fn app_with_plug_ins(exe: &Path, files: &[String]) -> std::process::Command {
let mut command = std::process::Command::new(exe);
command.arg("--").args(files);
command.args(super::launch_profile::child_args(files));
command
}
+2 -1
View File
@@ -50,7 +50,8 @@ fn command_line_files_wait_for_the_choice_about_a_stopped_plug_in() {
..Default::default()
};
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), services);
app.ui.stopped_plugin = Some(serde_json::json!({"id": "test.held", "name": "Held"}));
let held = serde_json::json!({"id": "test.held", "name": "Held"});
app.ui.stopped_plugin = Some(serde_json::json!({"item": held, "items": [held]}));
assert_eq!(open_or_hold(&mut app, files.clone()), files, "held while the choice is up");
assert!(read.borrow().is_empty(), "nothing opened before the choice");
app.ui.stopped_plugin = None;
+11
View File
@@ -31,6 +31,10 @@ artwork. Licence: see `LICENSE.txt`.
| `vectorcraft.ico` | Windows icon, 16 to 256 px | `apps/vectorcraft/build.rs` (embedded in the `.exe`) |
| `hicolor/<size>/apps/ai.storyteller.vectorcraft.png` | Linux theme icons, 16 to 512 px; the 256 one is also the runtime icon on Windows and Linux, the 128 one the brand mark in the app bar and About box (`crates/ui-egui/src/brand.rs`) | `packaging/linux/ai.storyteller.vectorcraft.desktop` |
| `hicolor/scalable/apps/ai.storyteller.vectorcraft.svg` | Linux scalable icon | as above |
| `vectorcraft-nightly.png` | the full tile with a deeper field, 1024 px | the Nightly feed's art (`packaging/nightly-icons.py`) |
| `vectorcraft-nightly-1024.png` | the same tile with Apple's margin, 1024 px | the Nightly `.app` master |
| `vectorcraft-nightly.ico` | Windows icons for the Nightly executable, 16 to 256 px | `apps/vectorcraft/build.rs` when built for `nightly-v1` |
| `vectorcraft-nightly.icns` | macOS icon set for the Nightly `.app`, 16 to 1024 px | `packaging/macos/nightly.sh` |
## How it reaches each OS
@@ -47,3 +51,10 @@ artwork. Licence: see `LICENSE.txt`.
Edit or replace `vectorcraft.svg` (and `vectorcraft-small.svg`), then run `packaging/icons.sh`
(needs `resvg`; `iconutil` on macOS for the `.icns`). It writes every PNG, the `.ico` (via
`cargo xtask ico`) and the `.icns`.
The Nightly art comes from the committed stable art, not from a new drawing: `python3
packaging/nightly-icons.py` solves each pixel's field contribution from the three-colour palette
(`#e8573f`, `#0b0b0c`, `#efe9dc`), adds the deeper field (`#a83a24`) and leaves the figure (ink and
paper) exactly as it was, then scales every frame natively with ffmpeg and packs the `.ico` (32bpp
BGRA frames with AND masks up to 128, a PNG frame for 256) and the `.icns` (PNG frames). No badge,
no crescent and no letter: the field alone says Nightly.
Binary file not shown.

After

Width:  |  Height:  |  Size: 646 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 181 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 235 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="6" width="12" height="12"/><path d="M6 2v2M2 6h2M18 22v-2M22 18h-2"/></svg>

After

Width:  |  Height:  |  Size: 274 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20.5 3.5 14.75 9.25"/><path d="M13 7.5l3.5 3.5-3 3c-1 1-2.75 1-3.75 0s-1-2.75 0-3.75z"/><path d="M10.2 14.2C8.5 15.5 6 15 4.5 16.5S3.5 20.5 6 20.5 8.5 19 10 19.5s3.5-1 2.5-3-1.5-1.7-2.3-2.3z" fill="currentColor"/></svg>

After

Width:  |  Height:  |  Size: 413 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="8.5" r="5"/><path d="M13.5 12 17 15.5"/><path d="M3 20h18M4 20v-3.5M8 20v-2M12 20v-3.5M16 20v-2M20 20v-3.5"/></svg>

After

Width:  |  Height:  |  Size: 319 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3.5 L19.5 8 L19.5 16 L12 20.5 L4.5 16 L4.5 8 Z"/><path d="M8 12h8"/><circle cx="13.5" cy="12" r="1.8" fill="currentColor"/></svg>

After

Width:  |  Height:  |  Size: 326 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="6" width="12" height="12"/><path d="M6 2v2M2 6h2M18 22v-2M22 18h-2"/><rect x="11" y="2.5" width="9" height="11.5" stroke-dasharray="2 2"/></svg>

After

Width:  |  Height:  |  Size: 343 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="5" width="16" height="14"/></svg>

After

Width:  |  Height:  |  Size: 232 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="10" width="11" height="8" transform="rotate(-30 6 18)"/><circle cx="6" cy="18" r="1.5"/><path d="M19 10.5A15 15 0 0 0 13.5 5"/><path d="M14.56 7.27 13.5 5l2.49-.22"/></svg>

After

Width:  |  Height:  |  Size: 371 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="13" width="7" height="7" stroke-dasharray="2 2"/><rect x="4" y="4" width="16" height="16"/><path d="M12 12l5-5M13.5 7H17v3.5"/></svg>

After

Width:  |  Height:  |  Size: 332 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3.5 13 5 9.5 6 10 7.5 5 9 9l-.5.5 2 3-2.5-.5-1.5 1.5-1.5-1"/><path d="M15 10 21 20H9Z"/></svg>

After

Width:  |  Height:  |  Size: 288 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M13.8 10.8a1.2 1.2 0 0 1 1.2 1.2a2.4 2.4 0 0 1-2.4 2.4a3.6 3.6 0 0 1-3.6-3.6a4.8 4.8 0 0 1 4.8-4.8a6 6 0 0 1 6 6a7.2 7.2 0 0 1-7.2 7.2a8.4 8.4 0 0 1-8.4-8.4V5.6"/><circle cx="4.2" cy="4.4" r="1.6" fill="currentColor"/></svg>

After

Width:  |  Height:  |  Size: 417 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2 8l10 10 10-10"/><circle cx="12" cy="11.64" r="4.5"/></svg>

After

Width:  |  Height:  |  Size: 254 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 18h4c3 0 4-9 7-9s3 9 5.5 9h2.5"/><circle cx="13.5" cy="9.5" r="4"/></svg>

After

Width:  |  Height:  |  Size: 271 B

+7
View File
@@ -2192,6 +2192,13 @@ pub fn blend_steps(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<usize> {
StepCount::default().blend(keys, spec, Rail::new(keys, spec).as_ref()).0
}
/// Most steps the blends in `n` and its subtree make in all when drawn: a step that copies a
/// blend counts that blend's steps again, and each instance of a repeat counts its source's
/// steps again. Objects that are not blend steps count 0.
pub fn blend_steps_made(n: &Node) -> usize {
StepCount::default().node(n, false)
}
/// Does each pair of `keys` blended with `spec` ask for the same number of steps
/// ([`blend_step_count`]) when each coordinate it counts from moves by up to `length` points and,
/// for Smooth Color, the difference between keys of different colors by up to `color` (0 to 1)?
+12
View File
@@ -96,6 +96,18 @@ impl Unit {
_ => None,
}
}
/// The SVG length unit an export writes this unit's sizes in: the unit itself when SVG has it,
/// else an SVG unit of the same kind (inches for feet and yards, centimeters for meters,
/// millimeters for Q and Ha). `None` for points and pixels.
pub fn svg_unit(self) -> Option<Unit> {
match self {
Unit::Millimeters | Unit::Centimeters | Unit::Inches | Unit::Picas => Some(self),
Unit::FeetInches | Unit::Feet | Unit::Yards => Some(Unit::Inches),
Unit::Meters => Some(Unit::Centimeters),
Unit::Q | Unit::Ha => Some(Unit::Millimeters),
Unit::Points | Unit::Pixels => None,
}
}
pub const fn label(self) -> &'static str {
match self {
Unit::Points => "Points",
+1 -1
View File
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export EPS",
[],
None,
"{path?, level?: 2|3 (default; PostScript language level: 3 writes smooth gradients and masks transparent image pixels out, 2 steps gradients and writes those pixels white), previewFormat?: none|tiffBw|tiffColor (default: a TIFF preview other apps show), transparentPreview?: true (else on white), overprints?: preserve (default)|discard, flattenerPreset?: \"medium\" (default; high, low or a saved preset: flattener.presets.list), flattener?: {the options of object.flattenTransparency over the preset}, embedFonts?: true (type is always written as outlines, so no fonts are needed), includeLinkedFiles?: false (the embedded document keeps linked images whole, not just their previews), thumbnails?: true (a PNG thumbnail in the file), cmykPostScript?: true (RGB documents written in CMYK), compatibleGradients?: false (stepped gradients at level 3 too), selectedOnly?: false, useArtboards?: true (one file per chosen artboard, artboards?/range?, {stem}_{artboard}.eps, the bounding box the artboard; with two or more, also the central file {stem}.eps first: the whole document, the bounding box the visible art; none when no art shows) | false (one file, the bounding box the visible art, y up from the first artboard's bottom-left corner, even when artboards are named; the default when none are named), format?: \"eps\", artboard?: i | artboards?: [i…] | range?: \"1-3, 5\" (the artboards written; naming them without useArtboards works as useArtboards: true)} → {path, bytes, warnings, files?}; no path → {dataBase64, …}. Transparency is flattened with the preset (EPS has none); the native document rides along in comments, for reopening the file as it was. Same as document.export {format: eps}. A key EPS doesn't take, and an unknown key inside flattener, are refused",
"{path?, level?: 2|3 (default; PostScript language level: 3 writes smooth gradients and masks transparent image pixels out, 2 steps gradients and writes those pixels white), previewFormat?: none|tiffBw|tiffColor (default: a TIFF preview other apps show), transparentPreview?: true (else on white), overprints?: preserve (default; paper white fills and strokes knock out with document.setup discardWhiteOverprint; white linked to a spot swatch that has a color, at a tint above 0%, still overprints)|discard, flattenerPreset?: \"medium\" (default; high, low or a saved preset: flattener.presets.list), flattener?: {the options of object.flattenTransparency over the preset}, embedFonts?: true (type is always written as outlines, so no fonts are needed), includeLinkedFiles?: false (the embedded document keeps linked images whole, not just their previews), thumbnails?: true (a PNG thumbnail in the file), cmykPostScript?: true (RGB documents written in CMYK), compatibleGradients?: false (stepped gradients at level 3 too), selectedOnly?: false, useArtboards?: true (one file per chosen artboard, artboards?/range?, {stem}_{artboard}.eps, the bounding box the artboard; with two or more, also the central file {stem}.eps first: the whole document, the bounding box the visible art; none when no art shows) | false (one file, the bounding box the visible art, y up from the first artboard's bottom-left corner, even when artboards are named; the default when none are named), format?: \"eps\", artboard?: i | artboards?: [i…] | range?: \"1-3, 5\" (the artboards written; naming them without useArtboards works as useArtboards: true)} → {path, bytes, warnings, files?}; no path → {dataBase64, …}. Transparency is flattened with the preset (EPS has none); the native document rides along in comments, for reopening the file as it was. Same as document.export {format: eps}. A key EPS doesn't take, and an unknown key inside flattener, are refused",
has_doc,
export_eps
)]
+7
View File
@@ -849,6 +849,13 @@ impl ReadFile {
r
}
/// Is part of the read still to do ([`Self::finish_read`]): the policies and the color mode of a
/// file that stopped for its profile question, or the linked files and the type of an answered
/// one?
pub fn read_left(&self) -> bool {
self.rest.is_some() || self.links_left.is_some()
}
/// The rest of [`read_for_open_asking`], once: the color management policies with the profile
/// answer (or as the policy says without one), the color mode `colorMode` asks for, the linked
/// files and the type. The app runs it off the UI thread once the question is answered.
+18
View File
@@ -212,11 +212,29 @@ fn flattening_cropped_art_keeps_the_art_under_its_hidden_part() {
fn overprints_are_kept_or_discarded() {
let mut s = session(100.0, 100.0, 1);
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"ids": [id], "color": {"c": 100, "m": 0, "y": 0, "k": 0}})).unwrap();
s.execute("attributes.set", &json!({"ids": [id], "overprintFill": true})).unwrap();
let kept = postscript(&b64(&s.execute("document.exportEps", &json!({"previewFormat": "none"})).unwrap()));
assert!(kept.contains("true op\n"), "{kept}");
let dropped = postscript(&b64(&s.execute("document.exportEps", &json!({"previewFormat": "none", "overprints": "discard"})).unwrap()));
assert!(!dropped.contains("true op"));
// A white fill or stroke that overprints knocks out with Discard White Overprint (on by
// default), and overprints without it, as in PDF export.
let white = json!({"c": 0, "m": 0, "y": 0, "k": 0});
let filled = [json!({"ids": [id], "color": white}), json!({"ids": [id], "none": true})];
let stroked = [json!({"ids": [id], "none": true}), json!({"ids": [id], "color": white})];
for (i, [fill, stroke]) in [filled, stroked].iter().enumerate() {
s.execute("paint.setFill", fill).unwrap();
s.execute("paint.setStroke", stroke).unwrap();
s.execute("attributes.set", &json!({"ids": [id], "overprintFill": i == 0, "overprintStroke": i == 1})).unwrap();
s.execute("document.setup", &json!({"discardWhiteOverprint": true})).unwrap();
let knocked_out = postscript(&b64(&s.execute("document.exportEps", &json!({"previewFormat": "none"})).unwrap()));
assert!(!knocked_out.contains("true op"), "{i}: {knocked_out}");
s.execute("document.setup", &json!({"discardWhiteOverprint": false})).unwrap();
let overprinted = postscript(&b64(&s.execute("document.exportEps", &json!({"previewFormat": "none"})).unwrap()));
assert!(overprinted.contains("true op\n"), "{i}: {overprinted}");
}
}
#[test]
+322 -53
View File
@@ -43,6 +43,11 @@
//! A filter whose manifest lists `inputs` (plug-in API level 2) is also given the selected type,
//! images or symbol instances of those kinds, to read only: its output must return each of them
//! unchanged ([`objects::decode_output_with`]).
//!
//! A filter, or a live effect's command, whose manifest lists `context` (plug-in API level 3) is
//! also given the parts of the active document it names in `_context.document`, whether or not
//! anything is selected: the settings, artboards, layers and swatches, as plain values
//! ([`context`]).
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
@@ -52,10 +57,13 @@ use vectorcraft_doc::{Document, Effect, Node};
use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode};
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or};
use crate::store::StoreTurn;
use crate::store::{PluginLoad, StoreTurn};
use vectorcraft_plugins::permissions::{self, Grant, GrantToken, Permission};
mod context;
pub use context::{CONTEXT_FUEL_PER_ITEM, MAX_CONTEXT_BYTES, MAX_CONTEXT_ITEMS};
/// What a plug-in error looks like to the user. A run the caller cancelled changed nothing.
fn err(e: vectorcraft_plugins::Error) -> EngineError {
match e {
@@ -102,6 +110,9 @@ pub fn describe(p: &Plugin) -> Value {
if !m.inputs.is_empty() {
v["inputs"] = json!(m.inputs);
}
if !m.context.is_empty() {
v["context"] = json!(m.context);
}
if m.paint_output {
v["paintOutput"] = json!(true);
}
@@ -254,15 +265,25 @@ impl FilterRun {
params["_context"]["mode"] = json!("command");
params["_context"]["command"] = json!(cmd.id);
}
// The parts of the document its manifest asks for (`context`), selection or not. Each row
// costs the run [`context::CONTEXT_FUEL_PER_ITEM`] instructions.
let sections = m.context_sections();
let mut charged = 0;
if !sections.is_empty() && may.contains(&Permission::DocRead) {
let given = context::document_context(st, &sections, c)?;
params["_context"]["document"] = given.value;
charged = (given.items as u64).saturating_mul(context::CONTEXT_FUEL_PER_ITEM);
}
let params = serde_json::to_vec(&params).map_err(|e| bad(c, e.to_string()))?;
// The input and the parameters may use half the plug-in's memory together.
let capacity = (plugin.limits().max_memory_bytes / 2).min(i32::MAX as usize).saturating_sub(params.len());
let (input, read_only) = objects::encode_input_with(&st.doc, &inputs, &kinds, capacity).map_err(err)?;
let document = (st.uid, st.revision);
let limits = match s.prefs.plugin_instruction_budget {
let mut limits = match s.prefs.plugin_instruction_budget {
crate::PluginBudget::Normal => plugin.limits().clone(),
crate::PluginBudget::Large => plugin.large_limits(),
};
limits.fuel_base = limits.fuel_base.saturating_sub(charged);
Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document, limits })
}
@@ -296,11 +317,17 @@ impl FilterRun {
}
/// The limits it runs under: the plug-in's, with the Plug-in Instruction Budget in force when
/// it was made.
/// it was made, less what its document context costs.
pub fn limits(&self) -> &vectorcraft_plugins::Limits {
&self.limits
}
/// The parameters it hands the plug-in, `_context` included.
#[cfg(test)]
pub(crate) fn params_json(&self) -> Value {
serde_json::from_slice(&self.params).unwrap_or(Value::Null)
}
/// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the
/// session ([`FilterRun::run_with_calls`]).
pub fn calls(&self) -> bool {
@@ -1010,12 +1037,16 @@ thread_local! {
pub(crate) static BEFORE_GRANT_STORED: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
/// Tests: runs once on this thread when [`hold_plugin_changes`] finds the lock held and waits.
pub(crate) static WHILE_WAITING: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
/// Tests: runs once in the next `plugin.reload` on this thread after its load started and before
/// it installs, as another session loading a folder in between would.
pub(crate) static BEFORE_RELOAD_INSTALLS: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
}
/// Held by `plugin.install` from its first read of the grant until the store holds what it
/// installed, and throughout by `plugin.remove`, by loads of the stored plug-ins
/// ([`Session::load_stored_plugins`]) and by loads of a plug-ins folder: these run one after the
/// other across sessions.
/// installed, throughout by `plugin.remove`, and while the loads of the stored plug-ins
/// ([`Session::load_stored_plugins`]) and of a plug-ins folder install what they loaded: these run
/// one after the other across sessions. It is not held while the modules load, so a session's
/// plug-in commands don't wait for another session's loads.
static PLUGIN_CHANGES: Mutex<()> = Mutex::new(());
/// Takes [`PLUGIN_CHANGES`], waiting while another session holds it.
@@ -1033,6 +1064,21 @@ pub(crate) fn hold_plugin_changes() -> std::sync::MutexGuard<'static, ()> {
}
}
/// Takes [`PLUGIN_CHANGES`] when no other session holds it, without waiting.
pub(crate) fn try_hold_plugin_changes() -> Option<std::sync::MutexGuard<'static, ()>> {
match PLUGIN_CHANGES.try_lock() {
Ok(held) => Some(held),
Err(std::sync::TryLockError::Poisoned(e)) => Some(e.into_inner()),
Err(std::sync::TryLockError::WouldBlock) => None,
}
}
/// Tests: whether [`PLUGIN_CHANGES`] could be taken now.
#[cfg(test)]
pub(crate) fn plugin_changes_free() -> bool {
!matches!(PLUGIN_CHANGES.try_lock(), Err(std::sync::TryLockError::WouldBlock))
}
/// `plugin.install`: loads and checks the module, refuses `grant` and `allowHeavy` that neither an
/// [`InstallApproval`] for this module nor the session allows, one that asks for a heavy budget
/// unless `allowHeavy` says a person agreed, one that lists permissions no person has granted this
@@ -1282,31 +1328,61 @@ fn load_path(_: &str) -> Result<(Plugin, Vec<u8>)> {
Err(EngineError::Other("installing from a path is not available on the web; pass the module as `dataBase64`".into()))
}
/// The plug-in folder last loaded, the plug-in store whose grants it was loaded with, and what
/// happened.
static FOLDER: Mutex<Option<(String, Option<std::path::PathBuf>, Value)>> = Mutex::new(None);
/// The plug-in folder last loaded, the plug-in store whose grants it was loaded with, what
/// happened, the load whose report it is ([`FOLDER_LOADS`]), and whether a file failed because no
/// loader thread was left to load it ([`vectorcraft_plugins::loader::NO_THREAD`]), so that the next
/// [`sync_prefs`] loads the folder again.
type FolderRecord = (String, Option<std::path::PathBuf>, Value, u64, bool);
/// The [`FolderRecord`] of the plug-in folder last loaded.
static FOLDER: Mutex<Option<FolderRecord>> = Mutex::new(None);
/// The number of the last folder load [`sync_prefs`] or `plugin.reload` started. [`sync_prefs`]
/// keeps it in [`FOLDER`] while its load runs, so only that load replaces or clears the record, and
/// a `plugin.reload` keeps its report only when no load started after it.
static FOLDER_LOADS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// Loads the Additional Plug-ins Folder preference (`*.wasm`) when it is set and it, or the
/// session's plug-in store, has changed since the last load. Runs whenever preferences are applied
/// (startup, `prefs.set`). Native only.
pub(crate) fn sync_prefs(s: &Session) {
let folder = s.prefs.plugins_folder.trim();
/// (startup, `prefs.set`). With [`Session::load_plugins_in_background`] on, it returns while the
/// modules load, and `plugin.list` reports the folder as loading until they are installed. Off, it
/// returns once the folder's plug-ins are installed, also while another session is still loading
/// the same folder. Native only.
pub(crate) fn sync_prefs(s: &mut Session) {
let folder = s.prefs.plugins_folder.trim().to_string();
// In Safe Mode nothing loads, and the folder is loaded once it ends ([`load_prefs_folder`]).
if folder.is_empty() || safe_mode::active() {
return;
}
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
if last.as_ref().is_some_and(|(f, store, _)| f == folder && *store == s.plugin_dir) {
// This session's own load of the folder, still running, is waited for unless loads go on in the
// background.
if s.plugin_loads.iter().any(|l| matches!(l, PluginLoad::Folder(f) if f.loads(&folder, &s.plugin_dir))) {
if !s.plugin_loads_in_background {
s.finish_plugin_loads();
}
return;
}
*last = Some((folder.to_string(), s.plugin_dir.clone(), load_folder(s, folder)));
let token = {
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
// A folder another session is still loading is loaded here too: that load may end with its
// session, and this one returns once its own plug-ins are installed.
// A load in which a file found no thread to load it is tried again.
if last.as_ref().is_some_and(|(f, store, r, _, retry)| *f == folder && *store == s.plugin_dir && r["loading"] != true && !retry) {
return;
}
let token = FOLDER_LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
*last = Some((folder.clone(), s.plugin_dir.clone(), json!({"folder": folder, "loading": true}), token, false));
token
};
let load = start_folder(s, &folder, Some(token));
s.queue_plugin_load(PluginLoad::Folder(load));
}
/// The Additional Plug-ins Folder preference was cleared from `old`: when `old` is the folder last
/// loaded, it is forgotten, so setting the preference to it again loads it again.
pub(crate) fn forget_prefs_folder(old: &str) {
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
if last.as_ref().is_some_and(|(f, _, _)| f == old.trim()) {
if last.as_ref().is_some_and(|(f, _, _, _, _)| f == old.trim()) {
*last = None;
}
}
@@ -1326,42 +1402,232 @@ pub fn load_prefs_folder(s: &mut Session) {
sync_prefs(s);
}
/// Loads the plug-ins in `folder`, those that list permissions only when `s` has them granted
/// ([`Session::plugin_approved`], with the store's grants read once) → its report; saves the
/// disabled list when loading changed it.
/// The modules of a folder loading ([`registry::FolderLoad`]); the web build has none.
#[cfg(not(target_arch = "wasm32"))]
fn load_folder(s: &Session, folder: &str) -> Value {
if let Err(e) = crate::file_access::check_read(folder) {
return json!({"folder": folder, "error": e});
}
// A file in it may be a link to one elsewhere.
let allow = |f: &std::path::Path| match f.to_str() {
Some(f) => crate::file_access::check_read(f),
// A lossy name would check another file than the one loaded.
None if crate::file_access::current().is_none() => Ok(()),
None => Err(format!("automation path rejected: {} isn't valid text", f.display())),
};
// A `plugin.install` in another session or process finishes writing the store first. When the
// store can't be locked, the folder still loads, and the store isn't written.
let _held = hold_plugin_changes();
let turn = s.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld());
match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_folder_approver()) {
Ok(r) => {
for id in &r.loaded {
s.attach_plugin_storage(&turn, id);
}
if r.disabled_changed {
s.store_disabled_plugins_in(&turn);
}
json!({"folder": folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>(), "leftOut": r.left_out})
type FolderModules = registry::FolderLoad;
#[cfg(target_arch = "wasm32")]
type FolderModules = std::convert::Infallible;
/// A load of the plug-ins in a folder ([`start_folder`]), which [`install_folder`] installs as the
/// modules load and [`end_folder`] ends.
pub(crate) struct FolderPending {
folder: String,
/// The plug-in store whose grants it loads with.
store: Option<std::path::PathBuf>,
/// The load's number in [`FOLDER`] when [`end_folder`] keeps its report as the folder last
/// loaded ([`sync_prefs`]).
record: Option<u64>,
/// A `plugin.reload`'s load: [`end_folder`] keeps its report as the folder last loaded unless a
/// load started after it.
reload: bool,
/// The modules loading, or the report of a folder that can't be loaded; `None` once ended.
load: Option<std::result::Result<FolderModules, Value>>,
/// Whether the modules not installed yet were dropped ([`FolderPending::cancel`]).
canceled: bool,
}
impl FolderPending {
/// Whether every module has been installed or reported.
pub(crate) fn done(&self) -> bool {
match &self.load {
#[cfg(not(target_arch = "wasm32"))]
Some(Ok(load)) => load.done(),
#[cfg(target_arch = "wasm32")]
Some(Ok(never)) => match *never {},
Some(Err(_)) | None => true,
}
Err(e) => json!({"folder": folder, "error": e.to_string()}),
}
/// Starts the modules loading, unless they started already.
pub(crate) fn start(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(Ok(load)) = &mut self.load {
load.start();
}
}
/// The installs and removals its modules are checked against (`None`: the folder couldn't be
/// listed, or the load ended).
pub(crate) fn changes(&self) -> Option<&registry::LoadChanges> {
match &self.load {
#[cfg(not(target_arch = "wasm32"))]
Some(Ok(load)) => Some(load.changes()),
#[cfg(target_arch = "wasm32")]
Some(Ok(never)) => match *never {},
Some(Err(_)) | None => None,
}
}
/// [`FolderPending::changes`], to adopt an earlier load's.
pub(crate) fn changes_mut(&mut self) -> Option<&mut registry::LoadChanges> {
match &mut self.load {
#[cfg(not(target_arch = "wasm32"))]
Some(Ok(load)) => Some(load.changes_mut()),
#[cfg(target_arch = "wasm32")]
Some(Ok(never)) => match *never {},
Some(Err(_)) | None => None,
}
}
/// Whether something can be installed or reported now, without waiting.
pub(crate) fn ready(&mut self) -> bool {
match &mut self.load {
#[cfg(not(target_arch = "wasm32"))]
Some(Ok(load)) => load.ready(),
#[cfg(target_arch = "wasm32")]
Some(Ok(never)) => match *never {},
Some(Err(_)) | None => true,
}
}
/// Waits until the next module in file-name order has loaded or failed.
pub(crate) fn wait(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(Ok(load)) = &mut self.load {
load.wait();
}
}
/// Drops the modules not installed yet, leaving it [`FolderPending::done`]; [`end_folder`]
/// then keeps no report as the folder last loaded.
pub(crate) fn cancel(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(Ok(load)) = &mut self.load {
load.cancel();
}
self.canceled = true;
}
/// Whether it is a load of `folder` with the plug-in store `store`.
pub(crate) fn loads(&self, folder: &str, store: &Option<std::path::PathBuf>) -> bool {
self.folder == folder && self.store == *store
}
}
impl Drop for FolderPending {
/// A load dropped before it ended (its session closed) leaves no folder reported as loading, so
/// the next session that applies the preference loads it.
fn drop(&mut self) {
if let Some(token) = self.record.filter(|_| self.load.is_some()) {
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
if last.as_ref().is_some_and(|(_, _, _, t, _)| *t == token) {
*last = None;
}
}
}
}
/// Starts loading the plug-ins in `folder` on worker threads ([`registry::FolderLoad`]); `record`:
/// the load's number in [`FOLDER`], whose record [`end_folder`] replaces with the report.
#[cfg(not(target_arch = "wasm32"))]
fn start_folder(s: &Session, folder: &str, record: Option<u64>) -> FolderPending {
let pending =
|load| FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false };
if let Err(e) = crate::file_access::check_read(folder) {
return pending(Err(json!({"folder": folder, "error": e})));
}
// A file in it may be a link to one elsewhere. Each file is checked again on its worker
// thread, in the scope in force here (the automation roots and the script gate), as the
// folder itself was.
let scope = crate::file_access::ScopeHandle::capture_now();
let allow = move |f: &std::path::Path| {
scope.clone().run(|| match f.to_str() {
Some(f) => crate::file_access::check_read(f),
// A lossy name would check another file than the one loaded.
None if crate::file_access::current().is_none() => Ok(()),
None => Err(format!("automation path rejected: {} isn't valid text", f.display())),
})
};
// The modules start loading once the loads queued before them are done.
pending(registry::FolderLoad::list(std::path::Path::new(folder), allow).map_err(|e| json!({"folder": folder, "error": e.to_string()})))
}
#[cfg(target_arch = "wasm32")]
fn load_folder(_: &Session, folder: &str) -> Value {
json!({"folder": folder, "error": "plug-in folders are not available on the web"})
fn start_folder(s: &Session, folder: &str, record: Option<u64>) -> FolderPending {
let load = Err(json!({"folder": folder, "error": "plug-in folders are not available on the web"}));
FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false }
}
/// Installs what `load` has loaded so far, in file-name order up to the first module still
/// loading, without waiting: those that list permissions only when `s` has them granted
/// ([`Session::plugin_approved`], with the store's grants read once). Runs while
/// [`hold_plugin_changes`] and `turn` are held, so a `plugin.install` in another session or process
/// finishes writing the store first; when the store can't be locked, the folder still installs,
/// and the store isn't written.
pub(crate) fn install_folder(s: &mut Session, load: &mut FolderPending, turn: &StoreTurn) {
#[cfg(not(target_arch = "wasm32"))]
if let Some(Ok(load)) = &mut load.load
&& !load.done()
{
for id in load.install_ready(s.plugin_folder_approver()) {
s.attach_plugin_storage(turn, &id);
}
// A disabled plug-in's file matched by its id is saved in the same turn.
if load.disabled_changed() && s.store_disabled_plugins_in(turn) {
load.disabled_saved();
}
}
#[cfg(target_arch = "wasm32")]
let _ = (s, load, turn);
}
/// Ends `load` once [`FolderPending::done`], while [`hold_plugin_changes`] and `turn` are held, so
/// the grants of ids whose module lists no permissions are forgotten while no `plugin.install` can
/// record one for another module → its report; saves the disabled list when loading changed it.
pub(crate) fn end_folder(s: &mut Session, mut load: FolderPending, turn: &StoreTurn) -> Value {
let (report, retry) = match load.load.take() {
#[cfg(not(target_arch = "wasm32"))]
Some(Ok(modules)) => {
let r = modules.finish();
if r.disabled_changed {
s.store_disabled_plugins_in(turn);
}
let failed = r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>();
(json!({"folder": load.folder, "loaded": r.loaded, "failed": failed, "leftOut": r.left_out}), r.no_thread)
}
#[cfg(target_arch = "wasm32")]
Some(Ok(never)) => match never {},
Some(Err(report)) => (report, false),
None => (Value::Null, false),
};
if let Some(token) = load.record {
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
// A later load, or a `plugin.reload`, replaced it meanwhile. A canceled load leaves no
// folder reported, so the next session that applies the preference loads it. A
// `plugin.reload`'s report replaces the record unless a load started after it, or the
// folder couldn't be loaded.
let current = if load.reload {
FOLDER_LOADS.load(std::sync::atomic::Ordering::Relaxed) == token && report.get("error").is_none()
} else {
last.as_ref().is_some_and(|(_, _, _, t, _)| *t == token)
};
if current {
*last = if load.canceled { None } else { Some((load.folder.clone(), load.store.clone(), report.clone(), token, retry)) };
}
}
report
}
/// Loads the plug-ins in `folder` and installs them, waiting for every module → the report, which is
/// kept as the folder last loaded unless a load started after this one.
fn load_folder_now(s: &mut Session, folder: &str) -> Value {
let token = FOLDER_LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
let mut load = start_folder(s, folder, Some(token));
load.reload = true;
#[cfg(test)]
if let Some(between) = BEFORE_RELOAD_INSTALLS.take() {
between();
}
s.finish_plugin_load(PluginLoad::Folder(load))
}
/// Tests: the next [`sync_prefs`] treats the folder last loaded as one in which a file found no
/// loader thread to load it.
#[cfg(test)]
pub(crate) fn folder_found_no_thread() {
if let Some(record) = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
record.4 = true;
}
}
fn reload(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1373,11 +1639,12 @@ fn reload(s: &mut Session, p: &Value) -> Result<Value> {
if folder.is_empty() {
return Err(bad(C, "no folder: pass `path` or set Preferences › Plug-ins & Scratch Disks › Additional Plug-ins Folder"));
}
let report = load_folder(s, &folder);
// Loads started earlier install first, so this one's plug-ins replace theirs.
s.finish_plugin_loads();
let report = load_folder_now(s, &folder);
if let Some(e) = report.get("error").and_then(Value::as_str) {
return Err(EngineError::Other(e.to_string()));
}
*FOLDER.lock().unwrap_or_else(|e| e.into_inner()) = Some((folder, s.plugin_dir.clone(), report.clone()));
Ok(report)
}
@@ -1426,7 +1693,7 @@ fn shown_report(mut report: Value) -> Value {
}
fn list(_: &mut Session, _: &Value) -> Result<Value> {
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r)| shown_report(r.clone()));
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r, _, _)| shown_report(r.clone()));
let disabled: Vec<Value> = safe_mode::disabled().iter().map(shown_item).collect();
Ok(
json!({"plugins": registry::list().iter().map(|p| describe_installed(p)).collect::<Vec<_>>(), "folder": folder, "safeMode": safe_mode::active(), "disabled": disabled}),
@@ -1434,13 +1701,15 @@ fn list(_: &mut Session, _: &Value) -> Result<Value> {
}
/// `plugin.safeMode`: whether Safe Mode is on and why, the plug-ins disabled for the next launch,
/// and the plug-in the last launch was loading when it stopped while the user hasn't chosen yet.
/// and the plug-ins the last launch was loading when it stopped while the user hasn't chosen yet.
fn safe_mode_state(_: &mut Session, _: &Value) -> Result<Value> {
let pending: Vec<Value> = safe_mode::previous().iter().map(shown_item).collect();
Ok(json!({
"active": safe_mode::active(),
"source": safe_mode::source().map(safe_mode::Source::name),
"disabled": safe_mode::disabled().iter().map(shown_item).collect::<Vec<_>>(),
"pendingItem": safe_mode::previous().map(|i| shown_item(&i)),
"pendingItem": pending.first(),
"pendingItems": pending,
}))
}
@@ -1579,7 +1848,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List Plug-ins",
[],
None,
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
always,
list
),
@@ -1651,7 +1920,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Safe Mode",
[],
None,
"{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file; under automation read roots, a file outside them is named by its file name here and in pendingItem, and plugin.setEnabled takes that name), pendingItem: {id, file, name, label} | null (the plug-in the last launch was loading when it stopped, until the user chooses; it may not be what stopped it)}. Safe Mode is chosen at launch, never by a command",
"{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file; under automation read roots, a file outside them is named by its file name here and in pendingItem, and plugin.setEnabled takes that name), pendingItem: {id, file, name, label} | null (the first of pendingItems), pendingItems: [{id, file, name, label}] (the plug-ins the last launch was loading when it stopped, oldest first, until the user chooses; any of them, or none, may be what stopped it)}. Safe Mode is chosen at launch, never by a command",
always,
safe_mode_state
),
+147
View File
@@ -0,0 +1,147 @@
//! A plug-in run's document context (`_context.document`): the parts of the active document its
//! manifest's `context` asks for ([`ContextSection`]), read when the run is prepared, with or
//! without a selection. It holds plain values only: names, flags, rectangles and colors, never an
//! object, a file path or a link target.
use serde_json::{Value, json};
use vectorcraft_doc::{ColorMode, LayerColor, Node, NodeKind};
use vectorcraft_plugins::ContextSection;
use super::super::{Result, bad};
use crate::DocState;
/// Most rows (artboards, layers and sublayers, and swatches together) a document context holds.
pub const MAX_CONTEXT_ITEMS: usize = 10_000;
/// Most bytes the rows of a document context take as JSON.
pub const MAX_CONTEXT_BYTES: usize = 4 * 1024 * 1024;
/// Instructions each row costs: they come off the run's instruction budget.
pub const CONTEXT_FUEL_PER_ITEM: u64 = 1_000;
/// A document context, and the rows it holds.
pub(super) struct DocumentContext {
pub value: Value,
pub items: usize,
}
/// The document context of `sections` for a run of command `c` on `st`: `{revision}` and a key
/// for each section asked for. A document with more than [`MAX_CONTEXT_ITEMS`] rows in them, or
/// rows of more than [`MAX_CONTEXT_BYTES`], is an error, before any row is made in the first case.
pub(super) fn document_context(st: &DocState, sections: &[ContextSection], c: &str) -> Result<DocumentContext> {
let d = &st.doc;
let layers = if sections.contains(&ContextSection::Layers) { layer_rows(d) } else { Vec::new() };
let swatches = || super::super::swatch::listed_swatches(d, true, d.swatch_groups.iter().collect());
let mut items = 0;
for s in sections {
items += match s {
ContextSection::Settings => 0,
ContextSection::Artboards => d.artboards.len(),
ContextSection::Layers => layers.len(),
ContextSection::Swatches => swatches().count(),
};
}
let too_large = || {
bad(
c,
format!(
"the document information the plug-in asks for is too large to hand over: at most {MAX_CONTEXT_ITEMS} artboards, layers and swatches in {MAX_CONTEXT_BYTES} bytes"
),
)
};
if items > MAX_CONTEXT_ITEMS {
return Err(too_large());
}
let mut bytes = 0usize;
let mut row = |v: Value| -> Result<Value> {
bytes = bytes.saturating_add(serde_json::to_vec(&v).map_or(usize::MAX, |b| b.len() + 1));
if bytes > MAX_CONTEXT_BYTES { Err(too_large()) } else { Ok(v) }
};
let active = active_artboard(st);
let mut out = json!({"revision": st.revision});
for s in sections {
let value = match s {
ContextSection::Settings => {
let board = active.and_then(|i| d.artboards.get(i));
row(json!({
"name": st.title(),
"colorMode": match d.color_mode {
ColorMode::Rgb => "rgb",
ColorMode::Cmyk => "cmyk",
},
"units": d.units.label(),
"width": board.map(|a| a.rect.width()),
"height": board.map(|a| a.rect.height()),
"bleed": d.setup.bleed,
"rasterEffectsPpi": d.raster_ppi(),
"activeArtboard": board.map(|a| a.id),
}))?
}
ContextSection::Artboards => {
let rows = d.artboards.iter().enumerate().map(|(i, a)| {
let r = a.rect;
row(json!({"id": a.id, "index": i, "name": a.name, "rect": [r.x0, r.y0, r.x1, r.y1], "active": active == Some(i)}))
});
Value::Array(rows.collect::<Result<_>>()?)
}
ContextSection::Layers => {
let rows = layers.iter().map(|l| {
let n = l.node;
row(json!({
"id": n.id.0, "parentId": l.parent, "depth": l.depth, "name": n.display_name(),
"visible": n.visible, "locked": n.locked, "template": l.template, "color": l.color.label_text(),
"sublayers": l.sublayers, "current": st.active_layer == Some(n.id),
}))
});
Value::Array(rows.collect::<Result<_>>()?)
}
ContextSection::Swatches => {
let rows = swatches().map(|(w, g)| row(super::super::swatch::swatch_json(w, g)));
Value::Array(rows.collect::<Result<_>>()?)
}
};
out[s.name()] = value;
}
Ok(DocumentContext { value: out, items })
}
/// Is `n` a layer or sublayer?
fn is_layer(n: &Node) -> bool {
matches!(n.kind, NodeKind::Layer { .. })
}
/// A layer or sublayer, where it is in the layer tree, and what its row reports besides the
/// node's own name and flags.
struct LayerRow<'a> {
node: &'a Node,
/// Its parent layer's id; `None` for a top-level layer.
parent: Option<u64>,
/// 0 for a top-level layer, 1 for its sublayers, and so on.
depth: usize,
color: LayerColor,
template: bool,
/// The sublayers it holds directly.
sublayers: usize,
}
/// Every layer and sublayer of `d`, depth first in document order (bottom first within each
/// parent). The walk keeps its own stack, so deep nesting can't overflow the thread's.
fn layer_rows(d: &vectorcraft_doc::Document) -> Vec<LayerRow<'_>> {
let mut out = Vec::new();
let mut stack: Vec<(&Node, Option<u64>, usize)> = d.layers.iter().rev().map(|l| (l.as_ref(), None, 0)).collect();
while let Some((node, parent, depth)) = stack.pop() {
let NodeKind::Layer { color, template, children, .. } = &node.kind else { continue };
let sublayers = children.iter().filter(|c| is_layer(c)).count();
stack.extend(children.iter().rev().filter(|c| is_layer(c)).map(|c| (c.as_ref(), Some(node.id.0), depth + 1)));
out.push(LayerRow { node, parent, depth, color: *color, template: *template, sublayers });
}
out
}
/// The index of the view's active artboard ([`DocState::active_artboard`]): when the document no
/// longer has it, the artboard the document opened on, else the first; `None` with no artboards.
fn active_artboard(st: &DocState) -> Option<usize> {
let d = &st.doc;
let at = |id: Option<u32>| id.and_then(|id| d.artboards.iter().position(|a| a.id == id));
at(st.active_artboard).or_else(|| at(d.opened_artboard)).or((!d.artboards.is_empty()).then_some(0))
}
+5
View File
@@ -472,6 +472,11 @@ impl RecoveryStore for FolderStore {
Self::create_area(dir)?;
Self::own_area(dir)?;
}
// A read refuses a link (`read`), and a write must too: the atomic writer replaces the
// target of a link, which would put the copy over a file outside the store.
if std::fs::symlink_metadata(&f).is_ok_and(|m| m.file_type().is_symlink()) {
return Err(format!("{}: not a plain file", f.display()));
}
vectorcraft_format::write_atomic(&f, bytes).map_err(|e| Self::file_error(&f, &e))
}
fn remove(&self, name: &str) -> std::result::Result<(), String> {
+17 -7
View File
@@ -1012,18 +1012,28 @@ fn swatch_list(s: &mut Session, p: &Value) -> Result<Value> {
Some(g) => vec![d.swatch_groups.iter().find(|x| x.name == g).ok_or_else(|| bad("swatch.list", format!("no colour group `{g}`")))?],
None => d.swatch_groups.iter().collect(),
};
// The built-in Registration swatch lists after None, as the panel shows it.
let none = d.swatches.iter().take_while(|w| w.paint.is_none()).count();
let (specials, rest) = d.swatches.split_at(none);
let all = specials.iter().chain([vectorcraft_color::swatch::registration()]).chain(rest);
let ungrouped = all.filter(|_| only.is_none()).map(|w| swatch_json(w, None));
let grouped = groups.iter().flat_map(|g| g.swatches.iter().map(|w| swatch_json(w, Some(&g.name))));
let swatches: Vec<Value> = ungrouped.chain(grouped).collect();
let swatches: Vec<Value> = listed_swatches(d, only.is_none(), groups.clone()).map(|(w, g)| swatch_json(w, g)).collect();
let groups: Vec<Value> =
groups.iter().map(|g| json!({"name": g.name, "swatches": g.swatches.iter().map(|w| &w.name).collect::<Vec<_>>()})).collect();
Ok(json!({"swatches": swatches, "groups": groups}))
}
/// The swatches `swatch.list` lists, in its order, each with the name of the colour group it is
/// in: with `ungrouped`, the swatches outside groups (the built-in Registration swatch after None,
/// as the panel shows it), then those of `groups`.
pub(super) fn listed_swatches<'a>(
d: &'a Document,
ungrouped: bool,
groups: Vec<&'a SwatchGroup>,
) -> impl Iterator<Item = (&'a Swatch, Option<&'a str>)> + 'a {
let none = d.swatches.iter().take_while(|w| w.paint.is_none()).count();
let (specials, rest) = d.swatches.split_at(none);
let all = specials.iter().chain([vectorcraft_color::swatch::registration()]).chain(rest);
let ungrouped = all.filter(move |_| ungrouped).map(|w| (w, None));
let grouped = groups.into_iter().flat_map(|g| g.swatches.iter().map(move |w| (w, Some(g.name.as_str()))));
ungrouped.chain(grouped)
}
fn swatch_sort(s: &mut Session, _: &Value) -> Result<Value> {
s.edit("Sort Swatches", |d, _| {
// [None] and other bracketed specials stay first, like the reference app.
+8
View File
@@ -125,6 +125,14 @@ pub fn waits_for_tool_edit(id: &str) -> bool {
find_command(id).is_some_and(|spec| spec.journal || WAIT_FOR_TOOL_EDIT.contains(&id))
}
/// Does command `id` first install the plug-ins still loading on other threads
/// ([`crate::Session::finish_plugin_loads`])? Plug-in commands do, a plug-in's own commands
/// included, and so does every command that waits for a tool edit ([`waits_for_tool_edit`]);
/// queries that only read, and view commands, go ahead while the plug-ins load.
pub fn waits_for_plugin_loads(id: &str) -> bool {
id.starts_with(vectorcraft_plugins::PREFIX) || waits_for_tool_edit(id)
}
/// Journaled commands that write a file and change nothing in the document: with an object of a
/// dynamic symbol instance's art selected, they read the instance as queries do
/// ([`crate::Session::execute`]).
+35
View File
@@ -227,6 +227,14 @@ fn with_gate_reads_exempt<T>(exempt: bool, f: impl FnOnce() -> T) -> T {
f()
}
/// `scope`, or for a thread without one, the `process` roots in force now (none: unconfined).
fn resolved(scope: Option<Scope>, process: Option<&Arc<AutomationRoots>>) -> Scope {
scope.unwrap_or_else(|| match process {
Some(r) => Scope::Confined(r.clone()),
None => Scope::Unconfined,
})
}
/// This thread's scope, with the gate of the script command it runs, to carry to work it hands to
/// another thread ([`ScopeHandle::run`]).
#[derive(Clone, Debug)]
@@ -238,6 +246,15 @@ impl ScopeHandle {
Self(SCOPE.with(|s| s.borrow().clone()), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get))
}
/// [`ScopeHandle::capture`], except that a thread with no scope of its own takes the process's
/// roots as they are now ([`confine_process`]): work captured before the process is confined
/// stays unconfined on the thread that runs it, as it would have been had it run on the calling
/// thread at once.
pub fn capture_now() -> Self {
let scope = resolved(SCOPE.with(|s| s.borrow().clone()), PROCESS.get());
Self(Some(scope), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get))
}
/// Run `f` in the captured scope.
pub fn run<T>(self, f: impl FnOnce() -> T) -> T {
let Self(scope, gate, exempt) = self;
@@ -1327,6 +1344,24 @@ mod tests {
let _ = std::fs::remove_dir_all(base);
}
/// Work captured with [`ScopeHandle::capture_now`] before the process is confined stays
/// unconfined when it runs after; work captured with [`ScopeHandle::capture`] is confined then.
#[test]
fn a_scope_captured_now_stays_unconfined_after_the_process_is_confined() {
if !crate::tests::in_own_process("file_access::tests::a_scope_captured_now_stays_unconfined_after_the_process_is_confined") {
return;
}
let (base, roots) = folders("captured-process");
let outside = s(base.join("outside/secret.svg"));
let (now, plain) = std::thread::spawn(|| (ScopeHandle::capture_now(), ScopeHandle::capture())).join().unwrap();
assert!(confine_process(roots));
assert_eq!(now.run(|| check_read(&outside)), Ok(()), "captured now, before the process was confined");
assert!(plain.run(|| check_read(&outside)).is_err(), "captured plainly, run after the process was confined");
let later = std::thread::spawn(ScopeHandle::capture_now).join().unwrap();
assert!(later.run(|| check_read(&outside)).is_err(), "captured now, after the process was confined");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn device_names() {
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.svg", "NUL ", "COM¹", "Lpt²", "lpt³.txt"] {
+6 -1
View File
@@ -203,6 +203,11 @@ pub struct Session {
/// Where the plug-ins `plugin.install` installs are kept; `None`: only for the process
/// ([`Session::attach_plugin_store`]).
plugin_dir: Option<std::path::PathBuf>,
/// Plug-in loads running on worker threads, oldest first ([`Session::poll_plugin_loads`]).
plugin_loads: std::collections::VecDeque<store::PluginLoad>,
/// Whether the loads of the stored plug-ins and of the plug-ins folder go on after the call
/// that starts them ([`Session::load_plugins_in_background`]).
plugin_loads_in_background: bool,
/// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder
/// ([`Session::attach_scripts_dir`]).
scripts_dir: Option<std::path::PathBuf>,
@@ -453,7 +458,7 @@ mod session;
pub(crate) use command_sets::SELECTS_GIVEN_IDS;
#[cfg(test)]
use command_sets::given_ids;
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit};
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_plugin_loads, waits_for_tool_edit};
pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection};
pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY};
#[cfg(test)]
+1 -1
View File
@@ -326,7 +326,7 @@ impl Files {
/// The options a file of this run is parsed with, preprocessor lines aside.
pub(crate) fn options(&self) -> Options {
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, ..Options::default() }
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, e4x: true, ..Options::default() }
}
/// The `JSINCLUDE` folders of this process: absolute folders separated by `;`.
+1 -1
View File
@@ -2009,7 +2009,7 @@ impl Session {
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
// code the way the script does.
let es2015 = include::es2015_script(request.file.as_deref());
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, ..Options::default() };
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..Options::default() };
let strict = options.strict;
// A kept engine reads each run's code the way that run's script does.
let mut realm = match realm {
+2
View File
@@ -106,6 +106,8 @@ impl Session {
profile_dir: None,
color_settings_file: None,
plugin_dir: None,
plugin_loads: Default::default(),
plugin_loads_in_background: false,
scripts_dir: None,
metadata_templates_dir: None,
new_doc_profile_dir: None,
+7
View File
@@ -59,6 +59,13 @@ impl Session {
/// Execute a command by id. This is THE entry point for every frontend.
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
// Plug-ins still loading on other threads ([`Session::load_plugins_in_background`]) are
// installed before a plug-in command, its own commands included, and before a command that
// may edit, as they would have been before the window showed; a step of a batch waits for
// the plug-ins an earlier step started loading.
if self.plugins_loading() && crate::waits_for_plugin_loads(id) {
self.finish_plugin_loads();
}
self.revealing(|s| s.execute_unwatched(id, params))
}
+650 -67
View File
@@ -35,14 +35,16 @@
//! The files are untrusted input like any other: sizes and counts are capped, a file that does not
//! parse is skipped with a log record, and every write is atomic.
use std::collections::{BTreeMap, BTreeSet};
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::SystemTime;
use serde_json::Value;
use vectorcraft_pdf::{APP, PdfPreset, builtin_preset};
use vectorcraft_plugins::loader::{Job, Loads};
use vectorcraft_plugins::permissions::GrantToken;
use vectorcraft_plugins::safe_mode;
use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError};
@@ -170,6 +172,29 @@ fn list_files(dir: &Path, ext: &str) -> Vec<PathBuf> {
files
}
/// [`list_files`], each file with its stamp ([`file_stamp`]) from the same look at it.
fn list_stamped_files(dir: &Path, ext: &str) -> Vec<(PathBuf, (u64, SystemTime))> {
let Ok(entries) = std::fs::read_dir(dir) else { return vec![] };
let mut files: Vec<_> = entries
.filter_map(Result::ok)
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case(ext)))
.filter_map(|p| {
let m = std::fs::metadata(&p).ok().filter(std::fs::Metadata::is_file)?;
match m.modified() {
Ok(t) => Some((p, (m.len(), t))),
Err(e) => {
log::warn!("skipping the stored plug-in {}: {e}", p.display());
None
}
}
})
.collect();
files.sort_by_key(|(p, _)| p.file_name().map(|n| n.to_string_lossy().to_lowercase()));
files.truncate(MAX_STORE_FILES);
files
}
/// The content of `path` when it is at most `max` bytes; the file is never read past `max`.
pub(crate) fn read_capped(path: &Path, max: u64) -> Result<Vec<u8>, String> {
let bytes = read_past_cap(path, max).map_err(|e| e.to_string())?;
@@ -187,11 +212,243 @@ fn read_past_cap(path: &Path, max: u64) -> std::io::Result<Vec<u8>> {
Ok(bytes)
}
/// Plug-ins loading on worker threads, which [`Session::poll_plugin_loads`] and
/// [`Session::finish_plugin_loads`] install.
pub(crate) enum PluginLoad {
/// The plug-in store's ([`Session::load_stored_plugins`]).
Stored(StoredLoad),
/// The Additional Plug-ins Folder's ([`crate::cmd::plugin::sync_prefs`]).
Folder(crate::cmd::plugin::FolderPending),
}
impl PluginLoad {
/// Starts the modules loading, unless they started already.
fn start(&mut self) {
match self {
PluginLoad::Stored(load) => load.loads.begin(),
PluginLoad::Folder(load) => load.start(),
}
}
/// The installs and removals it checks its modules against (`None`: a folder that couldn't be
/// listed, or one ended already).
fn changes(&self) -> Option<&vectorcraft_plugins::registry::LoadChanges> {
match self {
PluginLoad::Stored(load) => Some(&load.changes),
PluginLoad::Folder(load) => load.changes(),
}
}
/// [`PluginLoad::changes`], to adopt an earlier load's.
fn changes_mut(&mut self) -> Option<&mut vectorcraft_plugins::registry::LoadChanges> {
match self {
PluginLoad::Stored(load) => Some(&mut load.changes),
PluginLoad::Folder(load) => load.changes_mut(),
}
}
/// Whether every module has been installed or skipped.
fn done(&self) -> bool {
match self {
PluginLoad::Stored(load) => load.next == load.files.len() && load.rest.is_empty(),
PluginLoad::Folder(load) => load.done(),
}
}
/// Whether something can be installed or ended now, without waiting.
pub(crate) fn ready(&mut self) -> bool {
match self {
PluginLoad::Stored(load) => load.next == load.files.len() || !load.loaded.is_empty() || load.loads.next_ready(),
PluginLoad::Folder(load) => load.ready(),
}
}
/// Waits until [`PluginLoad::ready`], starting the modules loading first ([`PluginLoad::start`]).
fn wait(&mut self) {
self.start();
match self {
PluginLoad::Stored(load) if load.loaded.is_empty() && load.next < load.files.len() => load.loads.wait_next(),
PluginLoad::Stored(_) => {}
PluginLoad::Folder(load) => load.wait(),
}
}
/// Drops the modules not installed yet ([`Session::cancel_plugin_loads`]), leaving it
/// [`PluginLoad::done`] with what it installed.
fn cancel(&mut self) {
match self {
PluginLoad::Stored(load) => {
load.loads = Loads::deferred(Vec::new());
load.loaded.clear();
load.next = load.files.len();
load.rest.clear();
}
PluginLoad::Folder(load) => load.cancel(),
}
}
/// Whether installing it takes the plug-in store's own turn, making the store folder (a
/// folder's plug-ins keep their settings and cache there), rather than one that goes ahead
/// without a store folder.
fn creates_store(&self) -> bool {
matches!(self, PluginLoad::Folder(_))
}
}
/// A stored plug-in file, with its stamp when it was listed ([`file_stamp`]; `None`: it couldn't be
/// read).
type StoredFile = (PathBuf, Option<FileStamp>);
/// The stored plug-ins loading from the plug-in store `dir`.
pub(crate) struct StoredLoad {
dir: PathBuf,
/// The files listed, in file-name order.
files: Vec<StoredFile>,
loads: Loads<StoredRead>,
/// Outcomes taken from `loads` and not installed yet, in order.
loaded: VecDeque<vectorcraft_plugins::Result<StoredRead>>,
/// The next file to install.
next: usize,
/// The store's grants this load removed, by id, because the module stored for the id lists no
/// permissions: a later file holding a module with that id that the grant covers still loads,
/// and the grant goes back to the store.
retired: BTreeMap<String, vectorcraft_plugins::permissions::Grant>,
/// Installs and removals elsewhere since the store was listed, which a module loaded before
/// them doesn't undo.
changes: vectorcraft_plugins::registry::LoadChanges,
/// The files listed after `files`, in file-name order, with their stamps from when the store was
/// listed, that wait for `files` to load because what is left of [`MAX_PLUGIN_STORE`] may not
/// cover them until the reads that fail give back what they didn't read
/// ([`list_stored_plugins`]).
rest: VecDeque<StoredFile>,
/// What is left of [`MAX_PLUGIN_STORE`]: the listed length of each file in `files` is taken
/// from it, and what a failed read didn't read of it is given back.
left: u64,
}
/// What a stored plug-in's load read of its file, at most its listed length, and the module.
pub(crate) struct StoredRead {
read: u64,
plugin: vectorcraft_plugins::Result<vectorcraft_plugins::Plugin>,
}
/// Tests: what runs before a stored module is read, given its path.
#[cfg(test)]
type StoredHook = Arc<dyn Fn(&Path) + Send + Sync>;
/// Tests: runs on the worker thread before the stored module at the path it is given is read.
#[cfg(test)]
pub(crate) static BEFORE_STORED_LOAD: Mutex<Option<StoredHook>> = Mutex::new(None);
#[cfg(test)]
fn before_stored_load(path: &Path) {
let hook = BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()).clone();
if let Some(hook) = hook {
hook(path);
}
}
/// Tests: runs on the worker thread once the stored module at the path it is given has loaded, and
/// before its file is read again to check that it still holds the module.
#[cfg(test)]
pub(crate) static AFTER_STORED_LOAD: Mutex<Option<StoredHook>> = Mutex::new(None);
#[cfg(test)]
fn after_stored_load(path: &Path) {
let hook = AFTER_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()).clone();
if let Some(hook) = hook {
hook(path);
}
}
/// Why a stored plug-in whose file changed between its listing and its install is skipped.
const CHANGED_WHILE_LOADING: &str = "it changed or went away while it loaded";
#[cfg(test)]
thread_local! {
/// Tests: the stored plug-in bytes a store listed on this thread may read ([`MAX_PLUGIN_STORE`]).
pub(crate) static PLUGIN_STORE_BUDGET: std::cell::Cell<u64> = const { std::cell::Cell::new(MAX_PLUGIN_STORE) };
}
/// The stored plug-in bytes one store's load reads, all files together ([`MAX_PLUGIN_STORE`]).
#[cfg(not(test))]
fn plugin_store_budget() -> u64 {
MAX_PLUGIN_STORE
}
#[cfg(test)]
fn plugin_store_budget() -> u64 {
PLUGIN_STORE_BUDGET.with(std::cell::Cell::get)
}
/// What a file over its cap is told (a detail after the file's name, in the log or an error).
fn too_large(max: u64) -> String {
format!("larger than {max} bytes")
}
/// Takes the stored plug-in files at the front of `rest`, in order, each one's listed length taken
/// from `left` → those files, and the jobs that load them, each reading no more than that length.
/// It stops at the first file that `left` doesn't cover but would if files taken before it failed to
/// read and gave back what they took; that file and the ones after it stay in `rest`. A file that
/// `left` wouldn't cover even then is skipped with a log record, and once nothing can be given back
/// to a used-up `left` the rest are, as when the files were read one after the other.
fn list_stored_plugins(rest: &mut VecDeque<StoredFile>, left: &mut u64) -> (Vec<StoredFile>, Vec<Job<StoredRead>>) {
let limits = vectorcraft_plugins::Limits::default();
let mut files = Vec::new();
let mut jobs = Vec::new();
// What the files taken so far took of `left`.
let mut taken = 0;
while let Some((path, stamp)) = rest.pop_front() {
let len = stamp.flatten().map_or(0, |(len, _)| len);
let most = *left + taken;
if most == 0 {
log::warn!("skipping the other stored plug-ins: they hold more than {MAX_PLUGIN_STORE} bytes together");
rest.clear();
break;
}
if len > most {
log::warn!("skipping the stored plug-in {}: {}", path.display(), too_large(most));
continue;
}
// An empty file too waits once `left` is used up.
if len > *left || *left == 0 {
rest.push_front((path, stamp));
break;
}
*left -= len;
taken += len;
let item = safe_mode::Item::file(path.display().to_string());
let (read, limits) = (path.clone(), limits.clone());
jobs.push(Job::new(Some(item), move || {
#[cfg(test)]
before_stored_load(&read);
let mut bytes = vec![];
let got = std::fs::File::open(&read).and_then(|f| f.take(len + 1).read_to_end(&mut bytes));
let plugin = match got {
Err(e) => Err(vectorcraft_plugins::Error::Io(e.to_string())),
Ok(_) if bytes.len() as u64 > len => Err(vectorcraft_plugins::Error::Io(too_large(len))),
Ok(_) => vectorcraft_plugins::Plugin::load(&bytes, limits),
};
#[cfg(test)]
after_stored_load(&read);
// A file replaced while its module loaded, by one that kept its length and modified time,
// is told apart by its content: it is read again here, within the load's deadline. The
// install then skips a file whose stamp changed since.
let plugin = plugin.and_then(|p| {
if std::fs::File::open(&read).is_ok_and(|f| holds(f, &bytes)) {
Ok(p)
} else {
Err(vectorcraft_plugins::Error::Io(CHANGED_WHILE_LOADING.into()))
}
});
// A read that failed part way read what `bytes` holds.
Ok(StoredRead { read: (bytes.len() as u64).min(len), plugin })
}));
files.push((path, stamp));
}
(files, jobs)
}
/// Whether `old` holds exactly `bytes`. It is read no further than one byte past their length, so a
/// large file is not read into memory.
pub(crate) fn holds(old: impl Read, bytes: &[u8]) -> bool {
@@ -230,8 +487,7 @@ fn write_atomic(_: &Path, _: &[u8]) -> std::io::Result<()> {
/// replaced or removed, so that every window locks the same file.
#[cfg(not(target_arch = "wasm32"))]
fn lock_store(dir: &Path) -> std::io::Result<std::fs::File> {
std::fs::create_dir_all(dir)?;
let file = std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(DISABLED_LOCK))?;
let file = open_store_lock(dir)?;
match file.try_lock() {
Ok(()) => return Ok(file),
Err(std::fs::TryLockError::WouldBlock) => {}
@@ -245,6 +501,30 @@ fn lock_store(dir: &Path) -> std::io::Result<std::fs::File> {
Ok(file)
}
/// [`DISABLED_LOCK`] in `dir`, opened (and made, with the folder) but not locked.
#[cfg(not(target_arch = "wasm32"))]
fn open_store_lock(dir: &Path) -> std::io::Result<std::fs::File> {
std::fs::create_dir_all(dir)?;
std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(DISABLED_LOCK))
}
/// [`lock_store`] without waiting: `None` while another window or process holds the lock.
#[cfg(not(target_arch = "wasm32"))]
fn try_lock_store(dir: &Path) -> std::io::Result<Option<std::fs::File>> {
let file = open_store_lock(dir)?;
match file.try_lock() {
Ok(()) => Ok(Some(file)),
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
Err(std::fs::TryLockError::Error(e)) => Err(e),
}
}
/// The browser has no folders to keep anything in.
#[cfg(target_arch = "wasm32")]
fn try_lock_store(_: &Path) -> std::io::Result<Option<std::fs::File>> {
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system"))
}
/// The browser has no folders to keep anything in.
#[cfg(target_arch = "wasm32")]
fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
@@ -445,78 +725,188 @@ impl Session {
}
/// Keep the plug-ins this session installs in `dir`, take the disabled plug-ins saved there
/// ([`DISABLED_FILE`]), and install the stored ones ([`Session::load_stored_plugins`]).
/// ([`DISABLED_FILE`]), and install the stored ones ([`Session::load_stored_plugins`]). Loads
/// still running from an earlier call are finished first.
pub fn attach_plugin_store(&mut self, dir: PathBuf) {
let path = dir.join(DISABLED_FILE);
self.finish_plugin_loads();
self.plugin_dir = Some(dir);
// A `plugin.install` in another session or process writes the store before this reads it.
let _held = crate::cmd::plugin::hold_plugin_changes();
let turn = self.plugin_store_turn_for_load();
let disabled = read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default();
safe_mode::set_disabled(disabled);
self.load_stored_plugins_in(&turn);
self.start_stored_plugins(true);
}
/// Install the plug-ins kept in the plug-in folder: none in Safe Mode, and none the user
/// disabled (matched by file name, which is made from the id). The launch marker names each
/// file while it loads. A module that doesn't load, and one that lists permissions the grants
/// there don't grant that very module ([`grant_covers`]), is skipped with a log record, and
/// stays in the folder with its grant. A grant for an id whose stored module lists no
/// permissions is forgotten; one that can't be removed from the grants file doesn't count for
/// any session in the process attached to the folder until the file can be written for the id
/// ([`Session::ignore_stored_grant`]). The folder is read and changed in one turn on it
/// ([`Session::plugin_store_turn_for_load`]).
/// disabled (matched by file name, which is made from the id). The modules load on worker
/// threads ([`vectorcraft_plugins::loader`]) and install in file-name order, whatever order
/// their loads finish in; the launch marker names each file while it loads. A module that
/// doesn't load (its load panicked or didn't finish in time included), one that changed or
/// went away while it loaded, and one that lists permissions the grants there don't grant that
/// very module ([`grant_covers`]), is skipped with a log record, and stays in the folder with
/// its grant. A grant for an id whose stored module lists no permissions is forgotten; one that
/// can't be removed from the grants file doesn't count for any session in the process attached
/// to the folder until the file can be written for the id ([`Session::ignore_stored_grant`]).
/// The folder is listed, and what loaded is installed and the folder changed, in turns on it
/// ([`Session::plugin_store_turn_for_load`]); the modules load between them. With
/// [`Session::load_plugins_in_background`] on, this returns while the modules load.
pub fn load_stored_plugins(&mut self) {
if self.plugin_dir.is_none() || safe_mode::active() {
return;
}
// A `plugin.install` in another session or process writes the store before this reads it.
let _held = crate::cmd::plugin::hold_plugin_changes();
let turn = self.plugin_store_turn_for_load();
self.load_stored_plugins_in(&turn);
self.start_stored_plugins(false);
}
/// [`Session::load_stored_plugins`] in `turn`, while [`crate::cmd::plugin::hold_plugin_changes`]
/// is held.
fn load_stored_plugins_in(&mut self, turn: &StoreTurn) {
/// [`Session::load_stored_plugins`]; `disabled`: first take the disabled plug-ins saved in the
/// folder ([`DISABLED_FILE`]).
fn start_stored_plugins(&mut self, disabled: bool) {
let Some(dir) = self.plugin_dir.clone() else { return };
// A `plugin.install` in another session or process writes the store before this lists it.
let held = crate::cmd::plugin::hold_plugin_changes();
let turn = self.plugin_store_turn_for_load();
if disabled {
let path = dir.join(DISABLED_FILE);
let saved = read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default();
safe_mode::set_disabled(saved);
}
if safe_mode::active() {
return;
}
let grants = self.counted_grants(&dir);
let limits = vectorcraft_plugins::Limits::default();
let mut left = MAX_PLUGIN_STORE;
let mut asks_nothing = BTreeSet::new();
for path in list_files(&dir, PLUGIN_EXT) {
if left == 0 {
log::warn!("skipping the other stored plug-ins: they hold more than {MAX_PLUGIN_STORE} bytes together");
break;
}
let module = vectorcraft_plugins::Limits::default().max_module_bytes as u64;
let mut rest = VecDeque::new();
let disabled: BTreeSet<String> = safe_mode::skipped_ids().iter().map(|id| file_stem(id)).collect();
for (path, stamp) in list_stamped_files(&dir, PLUGIN_EXT) {
let item = safe_mode::Item::file(path.display().to_string());
let stem = path.file_stem().map(|s| s.to_string_lossy().to_string());
let by_id = safe_mode::skipped_ids().iter().any(|id| stem.as_deref() == Some(file_stem(id).as_str()));
let by_id = path.file_stem().is_some_and(|s| disabled.contains(s.to_string_lossy().as_ref()));
if safe_mode::skipped(&item) || by_id {
log::info!("skipping the stored plug-in {}: disabled", path.display());
} else if stamp.0 > module {
log::warn!("skipping the stored plug-in {}: {}", path.display(), too_large(module));
} else {
rest.push_back((path, Some(Some(stamp))));
}
}
let mut left = plugin_store_budget();
let (files, jobs) = list_stored_plugins(&mut rest, &mut left);
// A change made after the listing, while `held` no longer stops one, is made elsewhere.
let mut changes = vectorcraft_plugins::registry::LoadChanges::default();
changes.start();
// The modules load after the turn, once the loads queued before them are done.
drop((turn, held));
let load =
StoredLoad { dir, files, loads: Loads::deferred(jobs), loaded: VecDeque::new(), next: 0, retired: BTreeMap::new(), changes, rest, left };
self.queue_plugin_load(PluginLoad::Stored(load));
}
/// Installs what the stored plug-ins' `load` has loaded so far, in file-name order up to the
/// first module still loading, without waiting ([`Session::load_stored_plugins`]), while
/// [`crate::cmd::plugin::hold_plugin_changes`] and `turn` are held.
fn install_stored_plugins(&mut self, load: &mut StoredLoad, turn: &StoreTurn) {
if load.next == load.files.len() && !load.rest.is_empty() {
// Every file listed so far is installed or skipped, and the reads that failed gave
// back their length: the files waiting for them are listed now.
let (files, jobs) = list_stored_plugins(&mut load.rest, &mut load.left);
load.files = files;
load.next = 0;
load.loads = Loads::start(jobs);
return;
}
load.loaded.extend(load.loads.ready());
if load.loaded.is_empty() {
return;
}
let dir = load.dir.clone();
// The grants file is read once for this turn. `written` holds whether it names each id
// whose grant this turn removed or put back.
let file = read_grants(&dir);
let mut grants = self.counted(
&dir,
match &file {
Ok(file) => file.grants.clone(),
Err(e) => {
log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why);
BTreeMap::new()
}
},
);
let mut written: BTreeMap<String, bool> = BTreeMap::new();
let named = |written: &BTreeMap<String, bool>, id: &str| {
written.get(id).copied().unwrap_or_else(|| match &file {
Ok(file) => file.names(id),
Err(e) => e.unread,
})
};
while let (Some(loaded), Some((path, stamp))) = (load.loaded.pop_front(), load.files.get(load.next)) {
load.next += 1;
load.loads.release(1);
// What a read that failed didn't read takes nothing from the total. A load that panicked
// or passed its deadline gives nothing back.
let loaded = loaded.and_then(|r| {
load.left += stamp.flatten().map_or(0, |(len, _)| len).saturating_sub(r.read);
r.plugin
});
// The worker read the file again once its module loaded ([`list_stored_plugins`]); one
// whose stamp changed since then is skipped too.
if file_stamp(path).ok() != *stamp {
log::warn!("skipping the stored plug-in {}: {CHANGED_WHILE_LOADING}", path.display());
continue;
}
let token = safe_mode::loading(&item);
let loaded = read_capped(&path, (limits.max_module_bytes as u64).min(left)).and_then(|bytes| {
left -= bytes.len() as u64;
vectorcraft_plugins::Plugin::load(&bytes, limits.clone()).map_err(|e| e.to_string())
});
safe_mode::loaded(token);
match loaded {
Ok(plugin) if load.changes.superseded(plugin.id()) => {
log::warn!("skipping the stored plug-in {}: {}", path.display(), vectorcraft_plugins::registry::SUPERSEDED);
}
// Only this store's grants count: one given elsewhere in the process doesn't let a
// module stored here load.
Ok(plugin) if plugin.manifest().asks_permissions() => {
let m = plugin.manifest();
match grants.get(&m.id).filter(|g| grant_covers(g, &plugin)) {
let stored = grants.get(&m.id).filter(|g| grant_covers(g, &plugin)).cloned();
// A grant given for the id since this load removed one, in another window or
// process, is kept.
let back = (!grants.contains_key(&m.id) && !named(&written, &m.id))
.then(|| load.retired.get(&m.id).filter(|g| grant_covers(g, &plugin)).cloned())
.flatten();
match stored.or(back.clone()) {
Some(g) => {
asks_nothing.remove(&m.id);
vectorcraft_plugins::registry::grant(GrantToken::from_engine_grants_file(g.clone()));
vectorcraft_plugins::registry::set_storage(&m.id, plugin_storage(Some(&dir), &m.id, turn));
if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) {
log::warn!("skipping the stored plug-in {}: {e}", path.display());
// A grant this load removed for an earlier file with the id goes back. When
// it can't be written back, the module isn't installed: the store doesn't
// grant it, so it wouldn't load at the next launch either.
if back.is_some() {
if !self.store_grant_in(turn, &m.id, Some(g.clone())) {
log::warn!("skipping the stored plug-in {}: couldn't put back its grant", path.display());
continue;
}
load.retired.remove(&m.id);
written.insert(m.id.clone(), true);
grants.insert(m.id.clone(), g.clone());
}
let id = m.id.clone();
let token = GrantToken::from_engine_grants_file(g.clone());
// The storage is made before the plug-ins are held: making it reads the store.
let storage = plugin_storage(Some(&dir), &id, turn);
let attach = || vectorcraft_plugins::registry::set_storage(&id, storage);
// The id is checked for a change elsewhere again while the plug-ins are held.
let installed = match vectorcraft_plugins::registry::install_for_load(
plugin.with_source(path.display().to_string()),
&load.changes,
Some(token),
attach,
) {
Ok(Some(p)) => {
load.changes.installed(&p);
true
}
Ok(None) => {
log::warn!("skipping the stored plug-in {}: {}", path.display(), vectorcraft_plugins::registry::SUPERSEDED);
false
}
Err(e) => {
log::warn!("skipping the stored plug-in {}: {e}", path.display());
false
}
};
// A grant put back for a module that didn't install is removed again, so the
// store doesn't grant those bytes at the next launch.
if back.is_some() && !installed {
if self.store_grant_in(turn, &id, None) {
written.insert(id.clone(), false);
grants.remove(&id);
load.retired.insert(id, g);
} else {
log::warn!("couldn't remove the grant put back for the stored plug-in {}", path.display());
}
}
}
None => {
@@ -525,29 +915,213 @@ impl Session {
}
}
Ok(plugin) => {
asks_nothing.insert(plugin.id().to_string());
vectorcraft_plugins::registry::set_storage(plugin.id(), plugin_storage(Some(&dir), plugin.id(), turn));
if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) {
log::warn!("skipping the stored plug-in {}: {e}", path.display());
let id = plugin.id().to_string();
// The storage is made before the plug-ins are held: making it reads the store.
let storage = plugin_storage(Some(&dir), &id, turn);
let attach = || vectorcraft_plugins::registry::set_storage(&id, storage);
// The id is checked for a change elsewhere again while the plug-ins are held.
let p = match vectorcraft_plugins::registry::install_for_load(
plugin.with_source(path.display().to_string()),
&load.changes,
None,
attach,
) {
Ok(Some(p)) => p,
Ok(None) => {
log::warn!("skipping the stored plug-in {}: {}", path.display(), vectorcraft_plugins::registry::SUPERSEDED);
continue;
}
Err(e) => {
log::warn!("skipping the stored plug-in {}: {e}", path.display());
continue;
}
};
load.changes.installed(&p);
// In the same turn: the grants for the id stop counting, the process's and the
// store's, so no session sees the earlier module as approved. A module installed
// in its place meanwhile keeps the process's grant recorded for it.
vectorcraft_plugins::registry::revoke_if_installed(&id, p.serial());
if let Some(g) = grants.remove(&id) {
load.retired.insert(id.clone(), g);
}
if named(&written, &id) {
let writes = self.grant_writes();
if self.store_grant_in(turn, &id, None) {
written.insert(id.clone(), false);
} else if self.holds_plugin_grant(&id) {
self.ignore_stored_grant(&id, writes);
}
}
}
Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()),
}
}
let kept = read_grants(&dir);
for id in &asks_nothing {
vectorcraft_plugins::registry::revoke(id);
let named = match &kept {
Ok(file) => file.names(id),
Err(e) => e.unread,
}
/// Whether the loads of the stored plug-ins and of the Additional Plug-ins Folder go on after
/// the call that starts them ([`Session::attach_plugin_store`], [`Session::load_stored_plugins`],
/// preferences that set the folder): the app turns it on for its launch so that its window
/// shows while they load, installs what loaded with [`Session::poll_plugin_loads`] as its
/// frames go by, and turns it off once the launch's loads have started. Off (the default),
/// those calls return once what loaded is installed, the loads still running from before
/// included.
pub fn load_plugins_in_background(&mut self, on: bool) {
self.plugin_loads_in_background = on;
}
/// Installs what the plug-in loads have loaded so far, in the order the loads started and each
/// load's file-name order, up to the first module still loading, without waiting → whether
/// some are still loading. A load starts once the loads before it are done. When another
/// session or process is changing the plug-ins or the store, nothing installs until a later
/// call.
pub fn poll_plugin_loads(&mut self) -> bool {
while let Some(mut next) = self.plugin_loads.pop_front() {
next.start();
if !next.ready() {
self.plugin_loads.push_front(next);
return true;
}
let Some((held, turn)) = self.plugin_install_turn_now(next.creates_store()) else {
self.plugin_loads.push_front(next);
return true;
};
if named {
let writes = self.grant_writes();
if !self.store_grant_in(turn, id, None) && self.holds_plugin_grant(id) {
self.ignore_stored_grant(id, writes);
self.install_plugin_load(&mut next, &turn);
if !next.done() {
self.plugin_loads.push_front(next);
return true;
}
self.end_plugin_load(next, &turn);
drop((turn, held));
}
false
}
/// Waits for every plug-in load still running and installs what they loaded, in the order the
/// loads started. Plug-in commands, and commands that may edit, call it first
/// ([`Session::execute`]).
pub fn finish_plugin_loads(&mut self) {
while let Some(next) = self.plugin_loads.pop_front() {
self.finish_plugin_load(next);
}
}
/// Ends the plug-in loads still running without installing more of what they load: the app
/// calls it as it quits. Modules not started are dropped, and the ones running are given until
/// their deadline, so the launch marker is not left naming a plug-in that was loading. Each load
/// then ends as one that finished does for what it installed; a folder's end saves the disabled
/// list only when the store's turn can be taken without waiting.
pub fn cancel_plugin_loads(&mut self) {
while let Some(mut load) = self.plugin_loads.pop_front() {
load.cancel();
// A stored load's grants were settled as each module installed: its end writes nothing.
if !load.creates_store() {
self.end_plugin_load(load, &StoreTurn::unheld());
continue;
}
// Another session changing the plug-ins isn't waited for either: the folder's load then
// ends without the store's turn, so the grants of what it installed are still forgotten
// and the store isn't written.
let Some(held) = crate::cmd::plugin::try_hold_plugin_changes() else {
self.end_plugin_load(load, &StoreTurn::unheld());
continue;
};
// A store another window or process is using isn't waited for: the turn then isn't
// held, and the folder's end writes nothing to the store.
let turn = match self.plugin_dir.as_deref().map(try_lock_store) {
Some(Ok(Some(file))) => StoreTurn { lock: Some(file) },
_ => StoreTurn::unheld(),
};
self.end_plugin_load(load, &turn);
drop((turn, held));
}
}
/// Waits for `load`'s modules and installs them as they load, in turns on the store, then
/// ends it → its report (a folder's; `null` for the stored plug-ins).
pub(crate) fn finish_plugin_load(&mut self, mut load: PluginLoad) -> Value {
load.start();
loop {
load.wait();
let held = crate::cmd::plugin::hold_plugin_changes();
let turn = self.plugin_install_turn(load.creates_store());
self.install_plugin_load(&mut load, &turn);
if load.done() {
let report = self.end_plugin_load(load, &turn);
drop((turn, held));
return report;
}
}
}
/// A turn on the store for installing what a load loaded, taken after
/// [`crate::cmd::plugin::hold_plugin_changes`]: the folder's own turn
/// ([`Session::plugin_store_turn`]) when `create`, else one that goes ahead without a store
/// folder ([`Session::plugin_store_turn_for_load`]). One that can't be locked goes ahead
/// unheld.
fn plugin_install_turn(&self, create: bool) -> StoreTurn {
if create { self.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld()) } else { self.plugin_store_turn_for_load() }
}
/// [`crate::cmd::plugin::hold_plugin_changes`] and [`Session::plugin_install_turn`] without
/// waiting: `None` while another session holds the one or another window or process the other.
fn plugin_install_turn_now(&self, create: bool) -> Option<(MutexGuard<'static, ()>, StoreTurn)> {
let held = crate::cmd::plugin::try_hold_plugin_changes()?;
let turn = match self.plugin_dir.as_deref() {
Some(dir) if create || dir.is_dir() => match try_lock_store(dir) {
Ok(Some(file)) => StoreTurn { lock: Some(file) },
Ok(None) => return None,
Err(e) => {
log::warn!("can't lock {}: {e}", dir.join(DISABLED_LOCK).display());
StoreTurn::unheld()
}
},
_ => StoreTurn::unheld(),
};
Some((held, turn))
}
/// Whether plug-ins are still loading on worker threads ([`Session::load_plugins_in_background`]).
pub fn plugins_loading(&self) -> bool {
!self.plugin_loads.is_empty()
}
/// Keeps `load` to install after the loads started before it; without
/// [`Session::load_plugins_in_background`], waits for them all and installs what they loaded.
pub(crate) fn queue_plugin_load(&mut self, load: PluginLoad) {
self.plugin_loads.push_back(load);
// The first load starts now; one queued after it starts once those before it are done.
if let [only] = self.plugin_loads.make_contiguous() {
only.start();
}
if !self.plugin_loads_in_background {
self.finish_plugin_loads();
}
}
/// Installs what `load` has loaded so far, without waiting, in `turn`.
fn install_plugin_load(&mut self, load: &mut PluginLoad, turn: &StoreTurn) {
match load {
PluginLoad::Stored(load) => self.install_stored_plugins(load, turn),
PluginLoad::Folder(load) => crate::cmd::plugin::install_folder(self, load, turn),
}
}
/// Ends `load` once [`PluginLoad::done`], in `turn` → its report (a folder's).
fn end_plugin_load(&mut self, load: PluginLoad, turn: &StoreTurn) -> Value {
// The loads queued after it count what it installed as their own: one of theirs replaces
// it, as it would have with the loads run one after the other.
if let Some(ended) = load.changes() {
for later in &mut self.plugin_loads {
if let Some(changes) = later.changes_mut() {
changes.adopt(ended);
}
}
}
match load {
// A stored load's grants were settled as each module installed.
PluginLoad::Stored(_) => Value::Null,
PluginLoad::Folder(load) => crate::cmd::plugin::end_folder(self, load, turn),
}
}
/// Take a turn on the attached plug-in store ([`StoreTurn`]), waiting while another window or
@@ -659,8 +1233,17 @@ impl Session {
/// doesn't count for that folder ([`Session::ignore_stored_grant`]). The folder's key is worked
/// out on each call, so a path whose link now leads elsewhere is matched with where it leads.
fn counted_grants(&self, dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
self.counted(dir, stored_grants(dir))
}
/// `grants`, read from the plug-in store `dir`, without those the process doesn't count for
/// that folder ([`Session::counted_grants`]).
fn counted(
&self,
dir: &Path,
mut grants: BTreeMap<String, vectorcraft_plugins::permissions::Grant>,
) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
let key = plugin_store_key(dir);
let mut grants = stored_grants(dir);
let shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner());
for (_, id) in shared.ignored.range((key.clone(), String::new())..).take_while(|(folder, _)| *folder == key) {
grants.remove(id);
+706
View File
@@ -2196,6 +2196,550 @@ fn installed_plugins_are_kept_in_the_store() {
assert!(vectorcraft_plugins::registry::get(id).is_none());
}
/// Held by the tests that set [`crate::store::BEFORE_STORED_LOAD`].
static STORED_HOOK: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// A stored module's load waits on its worker thread until the test lets it go
/// ([`crate::store::BEFORE_STORED_LOAD`]). The hook is cleared when this is dropped.
struct HeldLoad {
_lock: std::sync::MutexGuard<'static, ()>,
entered: std::sync::Arc<std::sync::atomic::AtomicBool>,
go: std::sync::Arc<std::sync::atomic::AtomicBool>,
gave_up: std::sync::Arc<std::sync::atomic::AtomicBool>,
}
impl HeldLoad {
/// Holds the load of the file at `path`. A load the test never lets go gives up after a
/// million yields (so a test of code that waits for it ends) and says so in `gave_up`.
fn new(path: std::path::PathBuf) -> HeldLoad {
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
let lock = STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner());
let (entered, go, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)));
let (e, g, q) = (entered.clone(), go.clone(), gave_up.clone());
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(move |p: &std::path::Path| {
if p != path {
return;
}
e.store(true, Ordering::SeqCst);
if !(0..1_000_000).any(|_| {
std::thread::yield_now();
g.load(Ordering::SeqCst)
}) {
q.store(true, Ordering::SeqCst);
}
}));
HeldLoad { _lock: lock, entered, go, gave_up }
}
fn entered(&self) -> bool {
self.entered.load(std::sync::atomic::Ordering::SeqCst)
}
fn release(&self) {
self.go.store(true, std::sync::atomic::Ordering::SeqCst);
}
fn gave_up(&self) -> bool {
self.gave_up.load(std::sync::atomic::Ordering::SeqCst)
}
}
impl Drop for HeldLoad {
fn drop(&mut self) {
self.release();
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
}
/// A store holding the module of a filter `id` in `<id>.wasm`.
fn store_with(name: &str, id: &str) -> (crate::tests_links::Folder, std::path::PathBuf) {
let folder = crate::tests_links::Folder::new(name);
let path = folder.0.join(format!("{id}.wasm"));
std::fs::create_dir_all(&folder.0).unwrap();
std::fs::write(&path, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
(folder, path)
}
/// With loads in the background, attaching a plug-in store returns while a stored module is
/// still loading: the plug-in installs once its load is done, at the next plug-in command.
#[test]
fn a_store_attached_with_background_loads_returns_before_its_plugins_load() {
let id = "test.engine.background";
let (folder, path) = store_with("plugin-background", id);
let held = HeldLoad::new(path);
let mut s = session();
s.load_plugins_in_background(true);
s.attach_plugin_store(folder.0.clone());
let returned_while_loading = !held.gave_up();
while !held.entered() {
std::thread::yield_now();
}
assert!(returned_while_loading, "attaching the store waited for the module to load");
assert!(vectorcraft_plugins::registry::get(id).is_none(), "nothing installs before its load is done");
assert!(s.poll_plugin_loads(), "still loading");
held.release();
let listed = run(&mut s, "plugin.list", json!({}));
assert!(listed.to_string().contains(id), "plugin.list waits for the load and lists it: {listed}");
assert!(!s.poll_plugin_loads());
assert!(vectorcraft_plugins::registry::remove(id));
}
/// Stored files that can't be opened take nothing from the bytes the stored plug-ins may read
/// together: a module after 512 MiB of them still installs.
#[cfg(unix)]
#[test]
fn unreadable_stored_files_leave_the_store_budget_to_the_others() {
use std::os::unix::fs::PermissionsExt;
let id = "test.engine.budget.after";
let (folder, _) = store_with("plugin-budget-unreadable", id);
let per_file = vectorcraft_plugins::Limits::default().max_module_bytes as u64;
let locked: Vec<_> = (0..crate::store::MAX_PLUGIN_STORE.div_ceil(per_file))
.map(|n| {
// Sparse files sorted before the module, each as long as a module may be.
let path = folder.0.join(format!("a{n:03}.wasm"));
std::fs::File::create(&path).unwrap().set_len(per_file).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap();
path
})
.collect();
// A process that may read any file (root) opens them all: nothing to check.
if std::fs::File::open(&locked[0]).is_ok() {
return;
}
let mut s = session();
s.attach_plugin_store(folder.0.clone());
let installed = vectorcraft_plugins::registry::get(id).is_some();
for path in &locked {
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap();
}
assert!(installed, "the files that couldn't be opened used up the store's bytes");
assert!(vectorcraft_plugins::registry::remove(id));
}
/// A stored file whose read fails on the worker thread gives back what it took of the bytes the
/// stored plug-ins may read together, so a module after files that use them all up still installs.
#[test]
fn stored_files_whose_reads_fail_leave_the_store_budget_to_the_others() {
struct Unhook {
_lock: std::sync::MutexGuard<'static, ()>,
}
impl Drop for Unhook {
fn drop(&mut self) {
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
}
let id = "test.engine.budget.failed";
let (folder, module) = store_with("plugin-budget-failed", id);
let len = std::fs::metadata(&module).unwrap().len();
// Files sorted before the module, as long as it, that use up the bytes this test's store may read.
for n in 0..4 {
std::fs::write(folder.0.join(format!("a{n:03}.wasm")), vec![0; len as usize]).unwrap();
}
crate::store::PLUGIN_STORE_BUDGET.with(|b| b.set(4 * len));
let _unhook = Unhook { _lock: STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner()) };
// Each of those files goes away as its load starts, so its read fails.
let dir = folder.0.clone();
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(move |p: &std::path::Path| {
if p.parent() == Some(dir.as_path()) && p.file_name().is_some_and(|n| n.to_string_lossy().starts_with('a')) {
let _ = std::fs::remove_file(p);
}
}));
let mut s = session();
s.attach_plugin_store(folder.0.clone());
let installed = vectorcraft_plugins::registry::get(id).is_some();
crate::store::PLUGIN_STORE_BUDGET.with(|b| b.set(crate::store::MAX_PLUGIN_STORE));
assert!(installed, "the files whose reads failed used up the store's bytes");
assert!(vectorcraft_plugins::registry::remove(id));
}
/// A stored file replaced after its module loaded, by one of the same length with the same modified
/// time, is skipped: its content no longer holds the module. That holds for a file modified moments
/// ago and for one modified an hour ago.
#[test]
fn a_stored_file_replaced_with_the_same_stamp_while_it_loaded_is_skipped() {
struct Unhook {
_lock: std::sync::MutexGuard<'static, ()>,
}
impl Drop for Unhook {
fn drop(&mut self) {
*crate::store::AFTER_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
}
let _unhook = Unhook { _lock: STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner()) };
let hour = std::time::Duration::from_secs(3600);
// A modified time ahead of the clock counts as moments ago however long the test takes.
for (n, modified) in [std::time::SystemTime::now() + hour, std::time::SystemTime::now() - hour].into_iter().enumerate() {
let id = format!("test.engine.background.replaced{n}");
let (folder, path) = store_with(&format!("plugin-background-replaced{n}"), &id);
std::fs::File::options().write(true).open(&path).unwrap().set_modified(modified).unwrap();
let replaced = path.clone();
// Set once the file holds other bytes with the old stamp, so the case reaches the check.
let rewritten = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let done = rewritten.clone();
*crate::store::AFTER_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(move |p: &std::path::Path| {
if p == replaced {
let mut bytes = std::fs::read(p).unwrap();
bytes.reverse();
std::fs::write(p, &bytes).unwrap();
std::fs::File::options().write(true).open(p).unwrap().set_modified(modified).unwrap();
done.store(true, std::sync::atomic::Ordering::SeqCst);
}
}));
let mut s = session();
s.attach_plugin_store(folder.0.clone());
let installed = vectorcraft_plugins::registry::remove(&id);
assert!(rewritten.load(std::sync::atomic::Ordering::SeqCst), "the file was not replaced while it loaded ({n})");
assert!(!installed, "the module installed from a file that no longer holds it ({n})");
}
}
/// While a session loads the plug-ins folder in the background, another session's `plugin.list`
/// reports the folder as loading; once the load installs, it reports what loaded.
#[test]
fn another_session_lists_a_folder_still_loading_as_loading() {
// Other tests' `prefs.set` replaces the folder last loaded, which the process keeps.
if !in_own_process("another_session_lists_a_folder_still_loading_as_loading") {
return;
}
let id = "test.engine.listedloading";
let (folder, _) = store_with("plugin-listed-loading", id);
let mut background = session();
background.load_plugins_in_background(true);
run(&mut background, "prefs.set", json!({"values": {"pluginsFolder": folder.0.display().to_string()}}));
let mut other = session();
let listed = run(&mut other, "plugin.list", json!({}));
assert_eq!(listed["folder"]["loading"], true, "{listed}");
background.finish_plugin_loads();
let listed = run(&mut other, "plugin.list", json!({}));
assert!(vectorcraft_plugins::registry::remove(id));
assert_eq!(listed["folder"]["loaded"], json!([id]), "{listed}");
assert!(listed["folder"].get("loading").is_none(), "{listed}");
}
/// A `plugin.reload` doesn't replace the record of a folder load that started after it: once that
/// load installs, `plugin.list` reports its folder.
#[test]
fn a_reload_keeps_the_record_of_a_folder_load_started_after_it() {
// Other tests' `prefs.set` replaces the folder last loaded, which the process keeps.
if !in_own_process("a_reload_keeps_the_record_of_a_folder_load_started_after_it") {
return;
}
let (reloaded, later) = ("test.engine.reloadorder.reloaded", "test.engine.reloadorder.later");
let (reload_folder, _) = store_with("plugin-reload-order-reloaded", reloaded);
let (later_folder, _) = store_with("plugin-reload-order-later", later);
let other = std::rc::Rc::new(std::cell::RefCell::new(None));
let started = other.clone();
let path = later_folder.0.display().to_string();
// Another session sets the plug-ins folder while the reload loads.
crate::cmd::plugin::BEFORE_RELOAD_INSTALLS.set(Some(Box::new(move || {
let mut background = session();
background.load_plugins_in_background(true);
run(&mut background, "prefs.set", json!({"values": {"pluginsFolder": path}}));
*started.borrow_mut() = Some(background);
})));
let mut s = session();
run(&mut s, "plugin.reload", json!({"path": reload_folder.0.display().to_string()}));
let mut background = other.borrow_mut().take().expect("the other session's load started while the reload loaded");
background.finish_plugin_loads();
let listed = run(&mut s, "plugin.list", json!({}));
assert!(vectorcraft_plugins::registry::remove(reloaded) && vectorcraft_plugins::registry::remove(later));
assert_eq!(listed["folder"]["loaded"], json!([later]), "{listed}");
}
/// The plug-ins folder already loaded isn't loaded again when the preferences are applied, unless
/// a file in it found no loader thread to load it: then it is.
#[test]
fn a_folder_in_which_a_file_found_no_thread_is_loaded_again() {
if !in_own_process("a_folder_in_which_a_file_found_no_thread_is_loaded_again") {
return;
}
let id = "test.engine.nothread";
let (folder, _) = store_with("plugin-no-thread", id);
let mut s = session();
run(&mut s, "prefs.set", json!({"values": {"pluginsFolder": folder.0.display().to_string()}}));
assert!(vectorcraft_plugins::registry::remove(id), "installed from the folder");
crate::cmd::plugin::sync_prefs(&mut s);
assert!(vectorcraft_plugins::registry::get(id).is_none(), "a folder already loaded was loaded again");
crate::cmd::plugin::folder_found_no_thread();
crate::cmd::plugin::sync_prefs(&mut s);
assert!(vectorcraft_plugins::registry::remove(id), "the folder wasn't loaded again");
}
/// A folder listed while the stored plug-ins still load, in the same session, replaces a stored
/// plug-in with a module of the same id once it loads, as it does when the loads run one after the
/// other: what an earlier load of the session installed doesn't count as a change made elsewhere.
#[test]
fn a_folder_queued_behind_the_stored_plugins_replaces_one_with_its_id() {
let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner());
let id = "test.engine.queued.same";
let (store, stored) = store_with("plugin-queued-store", id);
let (folder, from_folder) = store_with("plugin-queued-folder", id);
let held = HeldLoad::new(stored);
let mut s = session();
s.load_plugins_in_background(true);
s.attach_plugin_store(store.0.clone());
while !held.entered() {
std::thread::yield_now();
}
s.prefs.plugins_folder = folder.0.display().to_string();
crate::cmd::plugin::sync_prefs(&mut s);
held.release();
s.finish_plugin_loads();
let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string));
assert!(vectorcraft_plugins::registry::remove(id));
assert_eq!(source.as_deref(), Some(from_folder.display().to_string().as_str()), "the folder's module replaces the stored one");
}
/// A query that only reads runs while the stored plug-ins load in the background, and doesn't
/// wait for them; a plug-in command does.
#[test]
fn a_query_runs_while_the_plugins_load() {
let id = "test.engine.background.query";
let (folder, path) = store_with("plugin-background-query", id);
let held = HeldLoad::new(path);
let mut s = session();
run(&mut s, "file.new", json!({}));
s.load_plugins_in_background(true);
s.attach_plugin_store(folder.0.clone());
while !held.entered() {
std::thread::yield_now();
}
run(&mut s, "document.info", json!({}));
let waited = held.gave_up() || !s.plugins_loading();
held.release();
assert!(!waited, "document.info waited for the plug-ins to load");
assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info"));
s.finish_plugin_loads();
assert!(vectorcraft_plugins::registry::remove(id));
}
/// The stored plug-ins load without holding the lock that `plugin.install` and `plugin.remove`
/// take, so another session's plug-in changes don't wait for them.
#[test]
fn stored_plugins_load_without_holding_the_plugin_changes_lock() {
let id = "test.engine.unlocked";
let (folder, path) = store_with("plugin-unlocked", id);
let held = HeldLoad::new(path);
let mut s = session();
s.load_plugins_in_background(true);
s.attach_plugin_store(folder.0.clone());
while !held.entered() && !held.gave_up() {
std::thread::yield_now();
}
// Other tests take the lock for a moment; the load holding it would hold it throughout (a
// tenth of the yields the held load waits before it gives up).
let free = (0..100_000).any(|_| {
std::thread::yield_now();
crate::cmd::plugin::plugin_changes_free()
});
// A load that gave up waiting no longer holds anything, so a free lock then shows nothing.
let gave_up = held.gave_up();
held.release();
s.finish_plugin_loads();
assert!(!gave_up, "the held load gave up before the lock was looked at");
assert!(free, "the lock was held while the module loaded");
assert!(vectorcraft_plugins::registry::remove(id));
}
/// Loads canceled as the app quits still end for what they installed: a stored module listing no
/// permissions that installed before a later one finished loading has its id's grant forgotten,
/// in the process and in `grants.json`, and the module still loading doesn't install.
#[test]
fn canceled_loads_forget_the_grants_of_what_they_installed() {
use vectorcraft_plugins::permissions::sha256_hex;
let (first, later) = ("test.engine.cancel.a", "test.engine.cancel.b");
let (folder, _) = store_with("plugin-cancel", first);
let held_path = folder.0.join(format!("{later}.wasm"));
std::fs::write(&held_path, wat::parse_str(tpl::returning(&tpl::manifest(later, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
let empty = json!({"objects": []});
let approved = asking(first, r#"["doc.read"]"#, &empty);
let grants = folder.0.join("grants.json");
let entry = json!([{"id": first, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]);
std::fs::write(&grants, serde_json::to_vec(&entry).unwrap()).unwrap();
let held = HeldLoad::new(held_path);
let mut s = session();
s.load_plugins_in_background(true);
s.attach_plugin_store(folder.0.clone());
while vectorcraft_plugins::registry::get(first).is_none() && !held.gave_up() {
s.poll_plugin_loads();
std::thread::yield_now();
}
assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads");
s.cancel_plugin_loads();
// The file goes once it holds no grant.
let listed: Vec<Value> = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default();
assert!(listed.iter().all(|e| e["id"] != first), "{listed:?}");
assert!(vectorcraft_plugins::registry::granted(first).is_none());
assert!(vectorcraft_plugins::registry::get(later).is_none(), "the module still loading doesn't install");
assert!(!s.plugins_loading());
drop(held);
assert!(vectorcraft_plugins::registry::remove(first));
}
/// The grants for a stored module that lists no permissions stop counting when it installs, in the
/// same turn, while a later module of the load is still loading.
#[test]
fn a_stored_module_without_permissions_ends_its_grant_when_it_installs() {
use vectorcraft_plugins::permissions::sha256_hex;
let (first, later) = ("test.engine.retire.a", "test.engine.retire.b");
let (folder, _) = store_with("plugin-retire", first);
let held_path = folder.0.join(format!("{later}.wasm"));
std::fs::write(&held_path, wat::parse_str(tpl::returning(&tpl::manifest(later, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
let empty = json!({"objects": []});
let approved = asking(first, r#"["doc.read"]"#, &empty);
let grants = folder.0.join("grants.json");
let entry = json!([{"id": first, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]);
std::fs::write(&grants, serde_json::to_vec(&entry).unwrap()).unwrap();
let held = HeldLoad::new(held_path);
let mut s = session();
s.load_plugins_in_background(true);
s.attach_plugin_store(folder.0.clone());
while vectorcraft_plugins::registry::get(first).is_none() && !held.gave_up() {
s.poll_plugin_loads();
std::thread::yield_now();
}
assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads");
assert!(s.plugins_loading(), "the second module is still loading");
let listed: Vec<Value> = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default();
assert!(listed.iter().all(|e| e["id"] != first), "{listed:?}");
assert!(vectorcraft_plugins::registry::granted(first).is_none());
drop(held);
s.finish_plugin_loads();
assert!(vectorcraft_plugins::registry::remove(first));
assert!(vectorcraft_plugins::registry::remove(later));
}
/// A grant the load removed for a stored module without permissions doesn't go back for a later
/// file with the same id when another window or process granted the id since: that grant stays, and
/// the later module, which it doesn't cover, is skipped.
#[test]
fn a_grant_given_elsewhere_since_the_load_removed_one_is_kept() {
use vectorcraft_plugins::permissions::sha256_hex;
let id = "test.engine.retire.kept";
let folder = crate::tests_links::Folder::new("plugin-retire-kept");
std::fs::create_dir_all(&folder.0).unwrap();
let empty = json!({"objects": []});
let (first, later) = (folder.0.join("a.wasm"), folder.0.join("b.wasm"));
std::fs::write(&first, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
let approved = asking(id, r#"["doc.read"]"#, &empty);
std::fs::write(&later, &approved).unwrap();
let grants = folder.0.join("grants.json");
let entry = |hash: String| serde_json::to_vec(&json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}])).unwrap();
std::fs::write(&grants, entry(sha256_hex(&approved))).unwrap();
let held = HeldLoad::new(later.clone());
let mut s = session();
s.load_plugins_in_background(true);
s.attach_plugin_store(folder.0.clone());
while vectorcraft_plugins::registry::get(id).is_none() && !held.gave_up() {
s.poll_plugin_loads();
std::thread::yield_now();
}
// Another process grants the id for another module while the later file loads.
let other = asking(id, r#"["doc.read"]"#, &json!({"objects": [{"path": triangle()}]}));
std::fs::write(&grants, entry(sha256_hex(&other))).unwrap();
drop(held);
s.finish_plugin_loads();
let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string));
assert!(vectorcraft_plugins::registry::remove(id));
let listed: Vec<Value> = serde_json::from_slice(&std::fs::read(&grants).unwrap()).unwrap();
assert_eq!(source.as_deref(), Some(first.display().to_string().as_str()), "the later module installed");
assert_eq!(listed.iter().map(|e| e["hash"].clone()).collect::<Vec<_>>(), [json!(sha256_hex(&other))], "{listed:?}");
}
/// A grant the load removed for a stored module without permissions that can't be written back for
/// a later file with the same id leaves that file's module uninstalled: the store doesn't grant it.
#[test]
fn a_grant_that_cannot_be_put_back_leaves_the_later_module_uninstalled() {
use vectorcraft_plugins::permissions::sha256_hex;
let id = "test.engine.retire.unwritten";
let folder = crate::tests_links::Folder::new("plugin-retire-unwritten");
std::fs::create_dir_all(&folder.0).unwrap();
let empty = json!({"objects": []});
let (first, later) = (folder.0.join("a.wasm"), folder.0.join("b.wasm"));
std::fs::write(&first, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
let approved = asking(id, r#"["doc.read"]"#, &empty);
std::fs::write(&later, &approved).unwrap();
let grants = folder.0.join("grants.json");
std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}])).unwrap()).unwrap();
// The first write removes the grant; the second, which puts it back, finds a folder where the
// file goes and fails.
let blocked = grants.clone();
crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || {
crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || {
let _ = std::fs::remove_file(&blocked);
std::fs::create_dir_all(&blocked).unwrap();
})));
})));
let mut s = session();
s.attach_plugin_store(folder.0.clone());
crate::store::AFTER_GRANTS_READ.set(None);
let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string));
let _ = std::fs::remove_dir(&grants);
assert!(vectorcraft_plugins::registry::remove(id));
assert_eq!(source.as_deref(), Some(first.display().to_string().as_str()), "the later module installed without its grant in the store");
}
/// A grant the load put back for a later stored file with the same id is removed again when that
/// file's module doesn't install because the id was installed elsewhere meanwhile: the store doesn't
/// grant bytes that weren't installed.
#[test]
fn a_grant_put_back_for_a_module_that_did_not_install_is_removed_again() {
use vectorcraft_plugins::permissions::sha256_hex;
let id = "test.engine.retire.superseded";
let folder = crate::tests_links::Folder::new("plugin-retire-superseded");
std::fs::create_dir_all(&folder.0).unwrap();
let empty = json!({"objects": []});
let (first, later) = (folder.0.join("a.wasm"), folder.0.join("b.wasm"));
let plain = wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap();
std::fs::write(&first, &plain).unwrap();
let approved = asking(id, r#"["doc.read"]"#, &empty);
std::fs::write(&later, &approved).unwrap();
let grants = folder.0.join("grants.json");
std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}])).unwrap()).unwrap();
// The first write removes the grant; while the second puts it back, the id is installed
// elsewhere.
crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || {
crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || {
vectorcraft_plugins::registry::install_bytes(&plain).unwrap();
})));
})));
let mut s = session();
s.attach_plugin_store(folder.0.clone());
crate::store::AFTER_GRANTS_READ.set(None);
let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string));
assert!(vectorcraft_plugins::registry::remove(id));
// A grants file that went away holds no grant; one still there must read as a list.
let listed: Vec<Value> = match std::fs::read(&grants) {
Ok(b) => serde_json::from_slice(&b).unwrap(),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => vec![],
Err(e) => panic!("the grants file could not be read: {e}"),
};
assert_eq!(source, None, "the later module replaced the one installed elsewhere");
assert!(listed.iter().all(|e| e["id"] != id), "the grant put back stayed in the store: {listed:?}");
}
/// A session that waits for its loads and sets the plug-ins folder another session is still
/// loading in the background loads the folder itself: its plug-in is installed when `prefs.set`
/// returns, and the other session's load, when it installs, counts the same module as loaded.
#[test]
fn a_folder_another_session_is_loading_is_loaded_by_a_session_that_waits() {
let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner());
let id = "test.engine.sharedfolder";
let (folder, _) = store_with("plugin-shared-folder", id);
let path = folder.0.display().to_string();
let mut background = session();
background.load_plugins_in_background(true);
run(&mut background, "prefs.set", json!({"values": {"pluginsFolder": path}}));
assert!(background.plugins_loading(), "the folder loads in the background");
let mut waits = session();
run(&mut waits, "prefs.set", json!({"values": {"pluginsFolder": path}}));
assert!(vectorcraft_plugins::registry::get(id).is_some(), "prefs.set returned before the folder's plug-in installed");
let report = run(&mut background, "plugin.list", json!({}));
assert!(!background.plugins_loading());
assert!(vectorcraft_plugins::registry::remove(id), "{report}");
}
/// A heavy test filter `id` that counts `steps` down, then adds a triangle named "Plug-in".
fn heavy(id: &str, steps: u64) -> Vec<u8> {
let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"filter","budget":"heavy"}}"#);
@@ -4085,6 +4629,168 @@ fn read_only_kind_field_and_omission_refuse_without_undo() {
assert!(e.contains("`inputs` needs `api` 2"), "{e}");
}
/// The manifest of a filter at `api` 3 with id `id` that asks for the document information
/// `context` (a JSON list), with `doc.read` and `doc.write`, and `rest` (keys after a comma, or
/// nothing).
fn context_manifest(id: &str, context: &str, rest: &str) -> String {
format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"context":{context}{rest}}}"#)
}
/// Installs `src` granted `doc.read` and `doc.write`, in place of any module with its id.
fn install_reading(s: &mut Session, src: &str) -> Value {
let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap());
run(s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true}))
}
/// A filter at `api` 3 whose manifest lists `context` is given the document's settings, artboards,
/// layers and swatches in `_context.document` with nothing selected: plain values, hidden and
/// locked layers with their flags, the active artboard and the current layer marked, and the
/// document's name without its folder. A filter that doesn't list `context` is given none, and one
/// that lists it without `doc.read` or below `api` 3 doesn't install.
#[test]
fn an_unselected_filter_reads_the_document_context_it_asks_for() {
use cmd::plugin::FilterRun;
let mut s = session();
run(&mut s, "artboard.new", json!({"x": 500, "y": 0, "width": 100, "height": 50}));
let hidden = run(&mut s, "layer.new", json!({"name": "Hidden", "visible": false}))["id"].as_u64().unwrap();
let locked = run(&mut s, "layer.newSublayer", json!({"parent": hidden, "name": "Locked", "locked": true}))["id"].as_u64().unwrap();
run(&mut s, "layer.setCurrent", json!({"id": locked}));
run(&mut s, "swatch.new", json!({"name": "Tone", "color": "#ff0000", "global": true}));
run(&mut s, "select.none", json!({}));
s.doc_mut().unwrap().path = Some("/private/folder/Poster.vectorcraft".into());
let second = s.doc().unwrap().doc.artboards[1].id;
s.doc_mut().unwrap().active_artboard = Some(second);
let id = "test.engine.context";
let all = r#"["settings","artboards","layers","swatches"]"#;
let installed = install_reading(&mut s, &tpl::returning(&context_manifest(id, all, ""), r#"{"objects":[]}"#));
assert_eq!(installed["context"], json!(["settings", "artboards", "layers", "swatches"]));
let swatches = run(&mut s, "swatch.list", json!({}))["swatches"].clone();
assert!(s.doc().unwrap().selection.objects.is_empty());
let given = FilterRun::prepare(&s, &json!({"id": id})).unwrap().params_json()["_context"]["document"].clone();
let st = s.doc().unwrap();
let d = &st.doc;
assert_eq!(given["revision"], json!(st.revision));
let board = &d.artboards[1];
let settings = json!({
"name": "Poster.vectorcraft", "colorMode": "rgb", "units": d.units.label(), "width": board.rect.width(),
"height": board.rect.height(), "bleed": d.setup.bleed, "rasterEffectsPpi": d.raster_ppi(), "activeArtboard": second,
});
assert_eq!(given["settings"], settings);
let boards: Vec<Value> = d
.artboards
.iter()
.enumerate()
.map(|(i, a)| json!({"id": a.id, "index": i, "name": a.name, "rect": [a.rect.x0, a.rect.y0, a.rect.x1, a.rect.y1], "active": i == 1}))
.collect();
assert_eq!((boards.len(), &given["artboards"]), (2, &json!(boards)));
let layers = given["layers"].as_array().unwrap();
let rows: Vec<(String, u64, bool, bool, bool)> = layers
.iter()
.map(|l| {
(l["name"].as_str().unwrap().to_string(), l["depth"].as_u64().unwrap(), l["visible"] == true, l["locked"] == true, l["current"] == true)
})
.collect();
let bottom = d.layers[0].display_name();
assert_eq!(rows, [(bottom, 0, true, false, false), ("Hidden".into(), 0, false, false, false), ("Locked".into(), 1, true, true, true)]);
assert_eq!((&layers[0]["parentId"], &layers[1]["sublayers"], &layers[2]["parentId"]), (&Value::Null, &json!(1), &json!(hidden)));
assert_eq!((&layers[1]["id"], &layers[2]["id"]), (&json!(hidden), &json!(locked)));
assert_eq!(given["swatches"], swatches, "as swatch.list lists them");
assert!(given["swatches"].as_array().unwrap().iter().any(|w| w["name"] == "Tone" && w["global"] == true));
assert!(!given.to_string().contains("/private/folder"), "no path: {given}");
// Only the sections asked for.
let some = "test.engine.context.some";
install_reading(&mut s, &tpl::returning(&context_manifest(some, r#"["layers"]"#, ""), r#"{"objects":[]}"#));
let given = FilterRun::prepare(&s, &json!({"id": some})).unwrap().params_json()["_context"]["document"].clone();
let keys: Vec<&String> = given.as_object().unwrap().keys().collect();
assert_eq!(keys.len(), 2, "{keys:?}");
assert!(given.get("layers").is_some() && given.get("revision").is_some());
// A filter without `context` is given none.
let legacy = "test.engine.context.legacy";
install_reading(&mut s, &tpl::returning(&tpl::manifest(legacy, "filter", "{}"), r#"{"objects":[]}"#));
assert!(FilterRun::prepare(&s, &json!({"id": legacy})).unwrap().params_json()["_context"].get("document").is_none());
// Without `doc.read`, or below `api` 3, it doesn't install.
let needs = "`context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read`";
for manifest in [
format!(r#"{{"id":"{some}","name":"x","kind":"filter","api":3,"permissions":["doc.write"],"context":["layers"]}}"#),
format!(r#"{{"id":"{some}","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"context":["layers"]}}"#),
] {
let data = vectorcraft_format::base64_encode(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap());
let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true})).unwrap_err();
assert!(e.to_string().contains(needs), "{manifest}: {e}");
}
}
/// A plug-in command, of a filter or of a live effect, whose manifest lists `context` is given it
/// too, with nothing selected.
#[test]
fn a_plugin_command_reads_the_document_context_without_a_selection() {
let mut s = session();
let made = json!({"objects": [{"path": triangle(), "name": "Saw layers"}]}).to_string();
for (id, kind, permissions) in [
("test.engine.context.command", "filter", r#"["doc.read","doc.write"]"#),
("test.engine.context.effectcommand", "effect", r#"["doc.read","doc.write","effect.render"]"#),
] {
let manifest = format!(
r#"{{"id":"{id}","name":"Test {id}","kind":"{kind}","api":3,"permissions":{permissions},"context":["layers"],"commands":[{{"id":"look","label":"Look"}}]}}"#
);
let src = tpl::when_given_else(&manifest, tpl::Given::Params, r#""layers":["#, &made, r#"{"objects":[]}"#);
let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap());
let grant: Vec<Value> = serde_json::from_str(permissions).unwrap();
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": grant, "replace": true}));
run(&mut s, "select.none", json!({}));
let ids = run(&mut s, &format!("plugin.{id}.look"), json!({}))["ids"].clone();
assert_eq!(ids.as_array().map(Vec::len), Some(1), "{kind}: {ids}");
assert_eq!(node(&s, NodeId(ids[0].as_u64().unwrap())).name.as_deref(), Some("Saw layers"), "{kind}");
}
}
/// A document context holds at most [`cmd::plugin::MAX_CONTEXT_ITEMS`] rows in
/// [`cmd::plugin::MAX_CONTEXT_BYTES`] bytes: past either, the run fails before the plug-in starts,
/// with the document and undo history as they were. Each row comes off the run's instruction
/// budget.
#[test]
fn the_document_context_is_capped_and_its_rows_cost_instructions() {
use cmd::plugin::{CONTEXT_FUEL_PER_ITEM, FilterRun, MAX_CONTEXT_BYTES, MAX_CONTEXT_ITEMS};
let mut s = session();
let id = "test.engine.context.cap";
install_reading(&mut s, &tpl::returning(&context_manifest(id, r#"["swatches"]"#, ""), r#"{"objects":[]}"#));
let p = json!({"id": id});
let listed = run(&mut s, "swatch.list", json!({}))["swatches"].as_array().unwrap().len();
let add = |s: &mut Session, n: usize| {
s.edit("Set up", |d, _| {
let base = d.swatches.last().unwrap().clone();
let at = d.swatches.len();
d.swatches.extend((at..at + n).map(|i| vectorcraft_color::Swatch { name: format!("Many {i}"), ..base.clone() }));
Ok(())
})
.unwrap();
};
add(&mut s, MAX_CONTEXT_ITEMS - listed);
let full = FilterRun::prepare(&s, &p).unwrap();
assert_eq!(full.params_json()["_context"]["document"]["swatches"].as_array().map(Vec::len), Some(MAX_CONTEXT_ITEMS));
assert_eq!(full.limits().fuel_base, full.plugin().limits().fuel_base - MAX_CONTEXT_ITEMS as u64 * CONTEXT_FUEL_PER_ITEM);
let too_large = "the document information the plug-in asks for is too large to hand over";
add(&mut s, 1);
let refused = |s: &mut Session| {
let Err(e) = FilterRun::prepare(s, &p) else { panic!("prepared past the cap") };
assert!(e.to_string().contains(too_large), "{e}");
let (doc, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
let e = s.execute("plugin.run", &p).unwrap_err().to_string();
assert!(e.contains(too_large), "{e}");
assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&doc, undo));
};
refused(&mut s);
// A few rows past the byte cap are refused as well.
run(&mut s, "edit.undo", json!({}));
run(&mut s, "edit.undo", json!({}));
s.edit("Set up", |d, _| {
d.swatches.last_mut().unwrap().name = "n".repeat(MAX_CONTEXT_BYTES);
Ok(())
})
.unwrap();
refused(&mut s);
}
/// A run past its memory budget fails before the plug-in starts, with the document and undo
/// history as they were: a read-only object whose other fields don't fit, a path and a compound
/// path that don't fit, and parameters past the input's half of the cap, with objects selected or
+16
View File
@@ -571,6 +571,22 @@ fn the_folder_store_reads_no_linked_entries() {
let _ = std::fs::remove_dir_all(&base);
}
/// A write to an entry that is a link (the copy's metadata names it) must not follow it out of the
/// store: the file behind the link keeps its bytes.
#[cfg(unix)]
#[test]
fn the_folder_store_writes_no_linked_entries() {
let base = std::env::temp_dir().join(format!("vc-recovery-write-links-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let store = FolderStore::new(&base);
store.write("1-1/Untitled-1-1.vectorcraft", b"copy").unwrap();
std::fs::write(base.join("outside"), b"private").unwrap();
std::os::unix::fs::symlink(base.join("outside"), base.join("1-1").join("img")).unwrap();
assert!(store.write("1-1/img", b"copy").is_err());
assert_eq!(std::fs::read(base.join("outside")).unwrap(), b"private");
let _ = std::fs::remove_dir_all(&base);
}
/// A file where a folder of the store's path should be: the error names that file, not the area
/// folder or the copy below it, for a write, a lock, a read, a listing, a removal and a recovery
/// save.
+73 -2
View File
@@ -326,8 +326,45 @@ fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() {
assert_eq!(modern["log"], json!([2]), "{modern}");
let legacy = s.execute("script.run", &path(&write("third.jsx", "#targetengine kept\nvc.log(k2);\nconst c = 1;")));
assert!(legacy.unwrap_err().to_string().contains("SyntaxError"));
let legacy = s.execute("script.run", &path(&write("fourth.jsx", "#targetengine kept\nvc.log(k2 + kept);"))).unwrap();
assert_eq!(legacy["log"], json!([3]), "{legacy}");
let fourth = "#targetengine kept\nvc.log(k2 + kept);\ntry { eval('let x = 1'); } catch (e) { vc.log(e.name); }";
let legacy = s.execute("script.run", &path(&write("fourth.jsx", fourth))).unwrap();
assert_eq!(legacy["log"], json!([3, "SyntaxError"]), "{legacy}");
// `for`-`of` and destructuring, in a new engine and in one a `.jsx` script made.
let loops = "var s = 0;\nfor (const [a, { b = 1 }] of [[1, {}], [2, { b: 3 }]]) s += a + b;\nvar { p, q: [r] } = { p: 4, q: [5] };\nvc.log(s);\nvc.log(p + r);\nvc.log(typeof Symbol);";
let r = s.execute("script.run", &path(&write("loops.js", loops))).unwrap();
assert_eq!(r["log"], json!([7, 9, "function"]), "{r}");
let kept = s
.execute("script.run", &path(&write("fifth.js", "#targetengine kept\nfor (const [i, ...j] of [[kept, 'x', 'y']]) vc.log(i + j.join(''));")))
.unwrap();
assert_eq!(kept["log"], json!(["1xy"]), "{kept}");
let e = s.execute("script.run", &path(&write("pattern.jsx", "var [a] = [1];"))).unwrap_err().to_string();
assert!(e.contains("SyntaxError"), "{e}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_js_script_reads_object_literal_extensions_and_function_names_and_a_jsx_script_does_not() {
let dir = fresh_folder("es2015-objects");
let write = |name: &str, text: &str| {
let p = dir.join(name);
std::fs::write(&p, text).unwrap();
p.to_string_lossy().into_owned()
};
let mut s = two_docs();
let path = |p: &str| json!({"path": p});
let modern = "var k = 'b';\nvar a = 1;\nvar o = { a, [k + 1]: 2, m() { return 3; }, f: () => 4 };\n\
vc.log(o.a + o.b1 + o.m() + o.f());\nvc.log(o.m.name + ',' + o.f.name + ',' + o.f.bind().name + ',' + Math.max.name);\n";
let r = s.execute("script.run", &path(&write("objects.js", modern))).unwrap();
assert_eq!(r["log"], json!([10, "m,f,bound f,max"]), "{r}");
for (name, text) in [("short.jsx", "var a = 1; var o = { a };"), ("computed.jsx", "var o = { ['b']: 1 };"), ("method.jsx", "var o = { m() {} };")]
{
let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string();
assert!(e.contains("SyntaxError"), "{name}: {e}");
}
let legacy = s.execute("script.run", &path(&write("names.jsx", "var f = function () {};\nvc.log(f.hasOwnProperty('name'));"))).unwrap();
assert_eq!(legacy["log"], json!([false]), "{legacy}");
// Script text given without a file keeps the ExtendScript language.
assert!(run(&mut s, "var a = 1; var o = { a };").unwrap_err().to_string().contains("SyntaxError"));
let _ = std::fs::remove_dir_all(&dir);
}
@@ -354,6 +391,40 @@ fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not()
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn every_script_reads_e4x_and_has_the_xml_objects() {
let dir = fresh_folder("e4x");
let write = |name: &str, text: &str| {
let p = dir.join(name);
std::fs::write(&p, text).unwrap();
p.to_string_lossy().into_owned()
};
let mut s = two_docs();
let path = |p: &str| json!({"path": p});
// Script text: literals, selectors, for each and the four constructors.
let text = "var x = <list><item id=\"a\">1</item><item id=\"b\">2</item></list>;\n\
vc.log(x.item.length() + ' ' + x.item.(@id == 'b').toString() + ' ' + x..item[0].@id);\n\
var sum = 0; for each (var i in x.item) sum += Number(i); vc.log(sum);\n\
vc.log(new XML('<a><b/></a>').b.length() + new XMLList('<c/><c/>').length());\n\
vc.log(new Namespace('p', 'urn:p').prefix + ' ' + new QName('urn:q', 'n').localName + ' ' + isXMLName('ok'));\n\
vc.log(typeof setDefaultXMLNamespace + ' ' + (1 < 2));\n";
let r = run(&mut s, text).unwrap();
assert_eq!(r["log"], json!(["2 2 a", 3, 3, "p n true", "function true"]), "{r}");
// A .js file, a file it includes, eval, Function and $.evalFile read XML as well.
write("lib.jsxinc", "var fromLib = <lib n=\"7\"/>.@n.toString();\n");
write("more.jsx", "<m>{fromLib}</m>.toString();\n");
let modern = "#include \"lib.jsxinc\"\nlet tag = <t>{fromLib}</t>;\nvc.log(tag.toString());\n\
vc.log(eval('<e>5</e>').toString());\nvc.log(new Function('return <f>6</f>.toString()')());\n\
vc.log($.evalFile(File($.fileName).parent + '/more.jsx'));\n";
let r = s.execute("script.run", &path(&write("modern.js", modern))).unwrap();
assert_eq!(r["log"], json!(["7", "5", "6", "7"]), "{r}");
// A named engine first made by a .js run gives a later .jsx run the XML objects too.
s.execute("script.run", &path(&write("first.js", "#targetengine xmlkept\nlet k = 1;"))).unwrap();
let later = s.execute("script.run", &path(&write("second.jsx", "#targetengine xmlkept\nvc.log(XML('<k>2</k>').toString());"))).unwrap();
assert_eq!(later["log"], json!(["2"]), "{later}");
let _ = std::fs::remove_dir_all(&dir);
}
/// A new empty folder for test `name`.
fn fresh_folder(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id()));
+10
View File
@@ -1463,6 +1463,16 @@ impl Session {
}
}
/// The object a click of the active tool at `p` with `mods` would act on
/// ([`vectorcraft_tools::Tool::hover_object`]), for Smart Guides › Object Highlighting. None
/// while Cmd lends a selection tool to the press ([`Self::lent_tool_at`]).
pub fn hover_object(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Option<NodeId> {
if mods.cmd && self.lender.is_none() && !self.tool_editing() && self.lent_tool_at(p, &mods, view).is_some() {
return None;
}
self.with_tool_cx(view, |t, cx| t.hover_object(cx, p, mods))
}
pub fn tool_options(&self) -> Value {
self.tool.options()
}
@@ -2,8 +2,8 @@
//! the tables below, and each name that reaches outside the document has the `outside` id
//! `script.check` (`vectorcraft-scriptcheck`) gives it. The names are read from a run: the own
//! properties of the global object, of each object or function it holds and of each function's
//! `prototype`, with a setter listed again as `name=`. The names a plain `vectorcraft_js::Realm` also
//! has are the language's, which reach files and other apps only through the host; `eval` and
//! `prototype`, with a setter listed again as `name=`. The names a plain `vectorcraft_js::Realm` with
//! E4X also has are the language's, which reach files and other apps only through the host; `eval` and
//! `Function` still have rows, since they run code the checker can't read. A name the host adds
//! without a row fails the test.
@@ -11,7 +11,7 @@ use std::collections::BTreeSet;
use serde_json::json;
use vectorcraft_engine::Session;
use vectorcraft_js::{DirectiveName, JsValue, Realm};
use vectorcraft_js::{DirectiveName, JsValue, Options, Realm};
use vectorcraft_scriptcheck::{Limits, check};
/// The names that reach outside the document: each with a script that uses it and the `outside` id
@@ -110,9 +110,9 @@ fn host_names() -> BTreeSet<String> {
text.lines().map(str::to_string).collect()
}
/// The names a plain JavaScript engine has.
/// The names a plain JavaScript engine with E4X has.
fn language_names() -> BTreeSet<String> {
match Realm::new().run(LIST) {
match Realm::with_options(Options { e4x: true, ..Options::default() }, vectorcraft_js::Limits::default()).run(LIST) {
Ok(JsValue::String(text)) => text.lines().map(str::to_string).collect(),
other => panic!("no list: {other:?}"),
}
+71
View File
@@ -906,6 +906,77 @@ proptest! {
vectorcraft_plugins::registry::revoke("fuzz.inputs");
}
/// Manifests with a hostile `context` (unknown, repeated and oddly cased sections, long lists,
/// junk of every type) with any `api`, kind and permissions parse to an error or to a filter, or
/// a live effect with commands, at `api` 3 or later asking for each section once, whose
/// `permissions` list `doc.read` so that installing it asks for approval. One that installs and
/// echoes its input, with or without a selection, leaves the document as it was, and it still
/// renders.
#[test]
fn hostile_manifest_context_never_crash(
kind in prop::sample::select(vec!["filter", "effect", "exporter"]),
commands in any::<bool>(),
names in prop::collection::vec(prop::sample::select(vec!["settings", "artboards", "layers", "swatches", "Layers", "document", ""]), 0..6),
long in prop::option::weighted(0.1, 5usize..300),
context in prop::option::weighted(0.8, prop_oneof![Just(Value::Null), arb_junk()]),
api in prop_oneof![2 => Just(json!(3)), 1 => Just(json!(2)), 1 => Just(json!(4)), 1 => arb_junk()],
permissions in prop_oneof![Just(Value::Null), Just(json!([])), Just(json!(["doc.read", "doc.write"])), Just(json!(["doc.read", "effect.render"])), Just(json!(["doc.write"]))],
select in any::<bool>(),
) {
let mut m = json!({"id": "fuzz.context", "name": "Context", "kind": kind, "api": api});
if kind == "exporter" {
m["extensions"] = json!(["fz"]);
}
if commands {
m["commands"] = json!([{"id": "c", "label": "C"}]);
}
if !permissions.is_null() {
m["permissions"] = permissions;
}
m["context"] = match (context, long) {
(_, Some(n)) => json!(vec!["layers"; n]),
(Some(Value::Null) | None, None) => json!(names),
(Some(junk), None) => junk,
};
let text = m.to_string();
let parsed = catch_quiet(|| vectorcraft_plugins::Manifest::parse(text.as_bytes()));
let parsed = parsed.map_err(|msg| TestCaseError::fail(format!("panicked on {text}: {msg}")))?;
if let Ok(man) = &parsed {
let sections = man.context_sections();
prop_assert_eq!(sections.len(), man.context.len(), "{}", text);
prop_assert!(sections.iter().enumerate().all(|(i, k)| !sections[..i].contains(k)), "{}", text);
let kind_ok = man.kind == Kind::Filter || (man.kind == Kind::Effect && !man.commands.is_empty());
prop_assert!(sections.is_empty() || (kind_ok && man.api >= 3), "{}", text);
let reads = man.permissions.as_ref().is_some_and(|p| p.iter().any(|n| n == "doc.read"));
prop_assert!(sections.is_empty() || (man.asks_permissions() && reads), "{}", text);
}
let mut s = rich_session();
s.allow_plugin_grants_from_requests();
let module = wat::parse_str(tpl::module(&text, tpl::ECHO, "", 1)).unwrap();
let data = vectorcraft_format::base64_encode(&module);
let grant = json!(["doc.read", "doc.write", "state", "effect.render", "export.write"]);
let before = s.doc().unwrap().doc.clone();
let r = catch_quiet(|| {
let installed = s.execute("plugin.install", &json!({"dataBase64": data, "grant": grant})).is_ok();
let _ = s.execute(if select { "select.all" } else { "select.none" }, &json!({}));
let ran = installed && s.execute("plugin.run", &json!({"id": "fuzz.context"})).is_ok();
if installed {
for c in s.commands().into_iter().filter(|c| c.id.starts_with("plugin.fuzz.context.")) {
let _ = s.execute(c.id, &json!({}));
}
}
(installed, ran)
});
let (installed, ran) = r.map_err(|msg| TestCaseError::fail(format!("panicked running {text}: {msg}")))?;
prop_assert!(!installed || parsed.is_ok(), "a manifest that doesn't parse installed: {}", text);
if ran {
prop_assert!(s.doc().unwrap().doc.layers == before.layers, "an echo changed the document: {}", text);
}
renders(&s, &text)?;
vectorcraft_plugins::registry::remove("fuzz.context");
vectorcraft_plugins::registry::revoke("fuzz.context");
}
/// A plug-in that calls the storage imports with hostile keys (`..`, separators, device names,
/// control characters, too long), values, lengths up to about 1 MiB and pointers in and out of
/// its memory runs to an output, or on a small budget to its instruction budget, never a panic;
+1 -1
View File
@@ -90,7 +90,7 @@ fn a_disabled_plug_in_stays_installed_and_loads_again_once_enabled_at_the_next_l
let list = s.execute("plugin.list", &json!({})).unwrap();
assert_eq!((list["safeMode"].clone(), list["disabled"][0]["id"].clone()), (json!(false), json!("test.sm.x")));
let state = s.execute("plugin.safeMode", &json!({})).unwrap();
assert_eq!(state, json!({"active": false, "source": null, "pendingItem": null, "disabled": state["disabled"].clone()}));
assert_eq!(state, json!({"active": false, "source": null, "pendingItem": null, "pendingItems": [], "disabled": state["disabled"].clone()}));
assert_eq!(state["disabled"].as_array().map(Vec::len), Some(1));
s.execute("plugin.setEnabled", &json!({"id": "test.sm.x", "enabled": true})).unwrap();
+48 -2
View File
@@ -132,6 +132,15 @@ fn over(under: Option<Paint>, art: &[Node]) -> Document {
/// Ink `ink`'s plate of `d` as the print plan separates it for PostScript, and as a PostScript
/// separation at `level` read back, both drawn at 1 px a point.
fn plate_of(d: &Document, ink: &str, level: Level) -> (Image, Image) {
let area = Rect::new(0.0, 0.0, 200.0, 100.0);
let (plate, out) = separation(d, ink, level);
let back = crate::import(&out.bytes).unwrap().document;
(render_region(&plate, area, 1.0), render_region(&back, area, 1.0))
}
/// Ink `ink`'s plate of `d` as the print plan separates it for PostScript, and that plate written
/// as a PostScript separation at `level`.
fn separation(d: &Document, ink: &str, level: Level) -> (Document, EpsOutput) {
let area = Rect::new(0.0, 0.0, 200.0, 100.0);
let settings = serde_json::from_value(serde_json::json!({"output": {"mode": "separations"}})).unwrap();
let plan = vectorcraft_pdf::plan(d, &vectorcraft_pdf::PrintOptions { settings, postscript: true, ..Default::default() }).unwrap();
@@ -151,8 +160,7 @@ fn plate_of(d: &Document, ink: &str, level: Level) -> (Image, Image) {
};
let out = print(&[page], &[0], &PrintJob { level, ..PrintJob::default() }).unwrap();
assert!(level == Level::Three || !text(&out).contains("shfill"), "Level 2 has no smooth shadings");
let back = crate::import(&out.bytes).unwrap().document;
(render_region(plate, area, 1.0), render_region(&back, area, 1.0))
(plate.clone(), out)
}
/// Ink `ink`'s PostScript plate of `art` over a page of 100% `ink` (`under`), checked against the
@@ -234,6 +242,44 @@ fn an_overprinting_gradient_keeps_the_ink_below_where_it_puts_none_on_a_postscri
assert_keeps_the_ink_below(&cases);
}
/// With Discard White Overprint, a process white fill or stroke marked to overprint knocks out the
/// cyan below it on the Cyan plate and is written without overprinting, as in composite output.
/// Without the setting, and for a white linked to a spot swatch with a color at a tint above 0%,
/// the cyan below it prints.
#[test]
fn white_overprints_knock_out_on_postscript_plates_with_discard_white_overprint() {
let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0));
let white = Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 0.0));
let spot_white = Paint::Solid { color: Color::cmyk(0.0, 0.0, 0.0, 0.0), swatch: Some("White Ink".into()), tint: 1.0 };
// The fill is sampled in the rectangle's middle, the stroke on its top edge.
let (fill_at, stroke_at) = ((100, 50), (100, 10));
let cases = [
("process white fill", overprinting(white.clone(), Paint::None), fill_at, true, true),
("process white stroke", overprinting(Paint::None, white.clone()), stroke_at, true, true),
("process white fill without the setting", overprinting(white.clone(), Paint::None), fill_at, false, false),
("process white stroke without the setting", overprinting(Paint::None, white), stroke_at, false, false),
("spot white fill", overprinting(spot_white.clone(), Paint::None), fill_at, true, false),
("spot white stroke", overprinting(Paint::None, spot_white), stroke_at, true, false),
];
let mut failed = vec![];
for (name, art, (x, y), discard, knocks_out) in cases {
let mut d = over(Some(cyan.clone()), &[art]);
d.swatches.push(Swatch { name: "White Ink".into(), paint: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 0.0)), global: true, spot: true });
d.setup.discard_white_overprint = discard;
for level in [Level::Three, Level::Two] {
let (_, printed) = plate_of(&d, "Cyan", level);
let paper = printed.over_white(x, y)[0] >= 254;
if paper != knocks_out {
failed.push(format!("{name} at level {level:?}: knocked out {paper}, expected {knocks_out}"));
}
if text(&separation(&d, "Cyan", level).1).contains("true op") {
failed.push(format!("{name} at level {level:?}: overprints on the plate"));
}
}
}
assert!(failed.is_empty(), "{failed:#?}");
}
#[test]
fn an_overprinting_gradient_with_a_hard_stop_at_an_end_keeps_the_ink_below_on_a_postscript_plate() {
// Two stops at an end, one with cyan and one without: Level 2's bands pad with the end stop,
+42 -13
View File
@@ -298,6 +298,8 @@ pub(crate) struct Scene<'a> {
/// The gradient being painted overprints on a plate: where it is paper white it puts none of
/// the plate's ink down, and the plate below it is left as it is ([`Self::inked_spans`]).
keep_below: bool,
/// Overprinting is on in the page's graphics state ([`Self::overprint_on`]).
overprinting: bool,
/// The print job's fonts: type in a solid fill is shown through them (`None`: drawn as
/// outlines).
fonts: Option<&'a RefCell<FontJob>>,
@@ -336,6 +338,7 @@ impl<'a> Scene<'a> {
nest: 0,
plate: false,
keep_below: false,
overprinting: false,
fonts: None,
used: UsedGlyphs::new(),
used_order: vec![],
@@ -535,11 +538,30 @@ impl<'a> Scene<'a> {
}
}
/// Turn overprinting on for one paint (when overprints are preserved); `false` when it stays off.
/// Whether a fill or stroke of `paint` marked to overprint (`overprint`) does: not when it is
/// paper white with Discard White Overprint in Output (Document Setup); a spot white still
/// overprints ([`Self::spot_ink`]). On a plate the colors are already the plate's coverage, and
/// the plate's document has already turned overprinting off for each white the setting knocks
/// out, so white is not checked there.
fn overprints(&self, overprint: bool, paint: &Paint) -> bool {
let discarded = !self.plate && self.doc.setup.discard_white_overprint && vectorcraft_doc::overprint::is_white(paint) && !self.spot_ink(paint);
overprint && !discarded
}
/// Whether `paint` is a tint above 0% of a spot swatch with a solid color, which the page writes
/// as a Separation ink of its own ([`Self::spot_space`]); a link is judged by the first swatch of
/// its name.
fn spot_ink(&self, paint: &Paint) -> bool {
matches!(paint, Paint::Solid { swatch: Some(name), tint, .. } if *tint > 0.0 && self.doc.swatch(name).is_some_and(|s| s.spot && s.paint.color().is_some()))
}
/// Turn overprinting on for one paint (when overprints are preserved); `false` when it stays off
/// or is already on (a pattern's tiles inside an overprinting pattern fill).
fn overprint_on(&mut self, overprint: bool) -> bool {
let on = overprint && self.o.overprint == Overprint::Preserve;
let on = overprint && self.o.overprint == Overprint::Preserve && !self.overprinting;
if on {
self.line("true op");
self.overprinting = true;
}
on
}
@@ -547,6 +569,7 @@ impl<'a> Scene<'a> {
fn overprint_off(&mut self, on: bool) {
if on {
self.line("false op");
self.overprinting = false;
}
}
@@ -611,7 +634,9 @@ impl<'a> Scene<'a> {
&& vectorcraft_doc::overprint::is_white(p)
&& vectorcraft_doc::overprint::DiscardWhite::of(self.doc).discards(p);
let on = self.overprint_on(n.colorize_overprints() && !discarded);
self.colorized_image(im, blob, p, on);
// Inside an overprinting pattern fill the image overprints with its tiles.
let overprinting = self.overprinting;
self.colorized_image(im, blob, p, overprinting);
self.overprint_off(on);
}
_ => self.image(&im.key, blob, im.width, im.height, im.xf),
@@ -729,7 +754,8 @@ impl<'a> Scene<'a> {
match item {
AppearanceItem::Fill(fl) if fl.visible && !fl.paint.is_none() => {
self.note_item(fl.opacity, fl.blend);
self.fill(bp, rule, &fl.paint, bounds, fl.overprint);
let overprint = self.overprints(fl.overprint, &fl.paint);
self.fill(bp, rule, &fl.paint, bounds, overprint);
}
AppearanceItem::Stroke(st) if st.visible && !st.paint.is_none() && st.width > 0.0 && st.width.is_finite() => {
self.stroke(bp, rule, st, bounds);
@@ -812,6 +838,7 @@ impl<'a> Scene<'a> {
return;
}
self.note_item(st.opacity, st.blend);
let overprint = self.overprints(st.overprint, &st.paint);
let paint_bounds = st.paint_bounds(bounds);
let area_paint = match &st.paint {
Paint::Pattern { .. } => true,
@@ -822,7 +849,7 @@ impl<'a> Scene<'a> {
// The area the stroke paints, as Outline Stroke makes it, painted with the pattern's
// tiles or the freeform's image.
let region = stroke::outline_region(&PathData::from_bezpath(bp), rule, st).to_bezpath();
self.fill(&region, FillRule::NonZero, &st.paint, paint_bounds, st.overprint);
self.fill(&region, FillRule::NonZero, &st.paint, paint_bounds, overprint);
return;
}
let w = stroke::for_writer(bp, st);
@@ -847,7 +874,7 @@ impl<'a> Scene<'a> {
};
match &w.shape {
WrittenShape::Stroke { width } => {
let on = self.overprint_on(st.overprint);
let on = self.overprint_on(overprint);
self.line_style(st, *width);
match &st.paint {
Paint::Solid { color, swatch, tint } => {
@@ -861,7 +888,7 @@ impl<'a> Scene<'a> {
self.line("q");
push_path(&mut self.body, bp);
self.line("strokepath W");
self.paint_overprinting(st.overprint, p, paint_bounds, w.reach(st, bounds));
self.paint_overprinting(overprint, p, paint_bounds, w.reach(st, bounds));
self.line("Q");
}
}
@@ -874,14 +901,14 @@ impl<'a> Scene<'a> {
push_path(&mut self.body, &ws.clip);
self.body.push_str(clip_op(FillRule::NonZero));
for (shape, paint) in &ws.slices {
self.fill(shape, FillRule::NonZero, paint, shape.bounding_box(), st.overprint);
self.fill(shape, FillRule::NonZero, paint, shape.bounding_box(), overprint);
}
self.line("Q");
}
}
WrittenShape::Fill(outlines) => {
for o in outlines {
self.fill(o, FillRule::NonZero, &st.paint, paint_bounds, st.overprint);
self.fill(o, FillRule::NonZero, &st.paint, paint_bounds, overprint);
}
}
}
@@ -989,12 +1016,13 @@ impl<'a> Scene<'a> {
if bp.elements().is_empty() {
continue;
}
let overprint = self.overprints(run.style.overprint_fill, &run.style.fill);
if fonts.is_none() {
self.fill(&bp, FillRule::NonZero, &run.style.fill, layout.bounds, run.style.overprint_fill);
self.fill(&bp, FillRule::NonZero, &run.style.fill, layout.bounds, overprint);
} else {
self.show(&shown, &run.style.fill, run.style.overprint_fill);
self.show(&shown, &run.style.fill, overprint);
if !art.elements().is_empty() {
self.fill(&art, FillRule::NonZero, &run.style.fill, layout.bounds, run.style.overprint_fill);
self.fill(&art, FillRule::NonZero, &run.style.fill, layout.bounds, overprint);
}
}
if run.style.has_stroke() {
@@ -1014,7 +1042,8 @@ impl<'a> Scene<'a> {
match item {
AppearanceItem::Fill(fl) if fl.visible && !fl.paint.is_none() => {
self.note_item(fl.opacity, fl.blend);
self.fill(bp, FillRule::NonZero, &fl.paint, tb, fl.overprint);
let overprint = self.overprints(fl.overprint, &fl.paint);
self.fill(bp, FillRule::NonZero, &fl.paint, tb, overprint);
}
AppearanceItem::Stroke(st) if st.visible && !st.paint.is_none() && st.width > 0.0 && st.width.is_finite() => {
self.stroke(bp, FillRule::NonZero, st, tb);
+121
View File
@@ -448,6 +448,106 @@ fn spot_colours_are_separations_and_overprints_are_kept_or_dropped() {
assert!(!page_of(&d, &EpsOptions { overprint: Overprint::Discard, ..opts(&d) }).contains("true op"));
}
/// Whether overprinting is on at each fill a page paints, by its `true op` and `false op` lines.
fn overprint_at_fills(page: &str) -> Vec<bool> {
let mut on = false;
let mut fills = vec![];
for line in page.lines() {
match line {
"true op" => on = true,
"false op" => on = false,
l if l == "f" || l.ends_with(" f") || l.ends_with(" f*") || l == "f*" => fills.push(on),
_ => {}
}
}
fills
}
#[test]
fn tiles_overprint_with_their_overprinting_pattern() {
// A rectangle filled with an overprinting pattern whose tile is a white square marked to
// overprint and then a cyan one that is not.
let mut d = doc_with(|_| vec![]);
let square = |d: &mut Document, paint: Paint, overprint: bool| {
let mut n = path(d, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), paint, Paint::None, 0.0);
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.overprint = overprint;
}
Arc::new(n)
};
let tile = vec![square(&mut d, Paint::solid(Color::WHITE), true), square(&mut d, Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)), false)];
d.patterns.push(vectorcraft_doc::PatternDef::new("tile", tile));
let mut n = red_rect(&mut d);
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.paint = Paint::Pattern { pattern: "tile".into(), xf: Affine::IDENTITY };
f.overprint = true;
}
let layer = d.layers[0].id;
d.insert(Some(layer), 0, n).unwrap();
// The whole pattern overprints, as in PDF export: the white square's own mark does not turn
// overprinting off for the cyan square after it, and Discard White Overprint applies to the
// pattern fill, not to its tiles.
let fills = overprint_at_fills(&page_of(&d, &opts(&d)));
assert!(!fills.is_empty() && fills.iter().all(|&on| on), "{fills:?}");
// On a plate too.
let plate = crate::scene::Scene::new(&d, &opts(&d)).on_plate(true).run();
let fills = overprint_at_fills(&plate.body);
assert!(!fills.is_empty() && fills.iter().all(|&on| on), "{fills:?}");
}
/// A white character fill, and a white fill of the type object itself, marked to overprint knock
/// out with Discard White Overprint and overprint without it.
#[test]
fn white_type_fills_knock_out_with_discard_white_overprint() {
use vectorcraft_doc::{CharStyle, FillLayer, TextObject};
let white = Paint::solid(Color::WHITE);
let char_fill = CharStyle { size: 30.0, fill: white.clone(), overprint_fill: true, ..CharStyle::default() };
let object_fill = CharStyle { size: 30.0, fill: Paint::None, ..CharStyle::default() };
for (i, style) in [char_fill, object_fill].into_iter().enumerate() {
let mut d = doc_with(|d| {
let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 100.0), "AB", style))));
if i == 1 {
n.appearance.items = vec![AppearanceItem::Fill(FillLayer { overprint: true, ..FillLayer::new(white.clone()) })];
}
vec![n]
});
let fills = overprint_at_fills(&page_of(&d, &opts(&d)));
assert!(!fills.is_empty() && fills.iter().all(|&on| !on), "{i}: {fills:?}");
d.setup.discard_white_overprint = false;
let fills = overprint_at_fills(&page_of(&d, &opts(&d)));
assert!(!fills.is_empty() && fills.iter().all(|&on| on), "{i}: {fills:?}");
}
}
/// Discard White Overprint applies to paper white only: a white fill linked to a spot swatch
/// still overprints, at 100% and 50%; one linked to a global process swatch, at a 0% tint of a
/// spot swatch, or to a spot swatch without a color (written as process) knocks out.
#[test]
fn spot_white_fills_overprint_with_discard_white_overprint() {
let white = Paint::solid(Color::WHITE);
let cases = [
(true, white.clone(), 1.0, true),
(true, white.clone(), 0.5, true),
(false, white.clone(), 1.0, false),
(true, white.clone(), 0.0, false),
(true, Paint::None, 1.0, false),
];
for (spot, swatch, tint, overprints) in cases {
let mut d = doc_with(|_| vec![]);
d.swatches.push(Swatch { name: "White Ink".into(), paint: swatch, global: true, spot });
let mut n = red_rect(&mut d);
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.paint = Paint::Solid { color: Color::WHITE, swatch: Some("White Ink".into()), tint };
f.overprint = true;
}
let layer = d.layers[0].id;
d.insert(Some(layer), 0, n).unwrap();
assert!(d.setup.discard_white_overprint);
let fills = overprint_at_fills(&page_of(&d, &opts(&d)));
assert_eq!(fills, vec![overprints], "spot: {spot}, tint: {tint}, expected to overprint: {overprints}");
}
}
const GOLD: Color = Color::Cmyk { c: 0.0, m: 0.2, y: 0.8, k: 0.1 };
const LEAF: Color = Color::Cmyk { c: 1.0, m: 0.0, y: 1.0, k: 0.0 };
@@ -1253,6 +1353,27 @@ fn an_overprinting_colorized_image_writes_only_its_process_inks() {
assert!(ps.contains("VCdn0 setcolorspace") && ps.contains("/DeviceCMYK setcolorspace"), "{ps}");
}
/// An overprinting colorized image in the tile of an overprinting pattern fill is written in only
/// the process inks it puts down, as it is outside a pattern, so the inks below it stay.
#[test]
fn an_overprinting_colorized_image_in_an_overprinting_pattern_writes_only_its_process_inks() {
let mut d = overprinting_colorized_doc(vec![0, 128, 255], Color::cmyk(1.0, 0.0, 0.0, 0.0), true);
let id = d.layers[0].children().unwrap()[0].id;
let image = d.remove(id).unwrap();
d.patterns.push(vectorcraft_doc::PatternDef::new("tile", vec![image]));
let mut n = red_rect(&mut d);
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.paint = Paint::Pattern { pattern: "tile".into(), xf: Affine::IDENTITY };
f.overprint = true;
}
let layer = d.layers[0].id;
d.insert(Some(layer), 0, n).unwrap();
for level in Level::ALL {
let ps = page_of(&d, &EpsOptions { level, ..opts(&d) });
assert!(ps.contains("true op") && ps.contains("VCdn0 setcolorspace") && !ps.contains("/DeviceCMYK setcolorspace"), "{level:?}: {ps}");
}
}
/// On a separation plate, an overprinting colorized image whose color puts none of the plate's ink
/// down is drawn as nothing, so the ink below stays; one that knocks out, or whose overprint is
/// discarded, is drawn as paper. (The plate's colors come from the separator, which has already
+77 -10
View File
@@ -82,15 +82,19 @@ pub enum PropertyKey {
Ident(String),
String(Vec<u16>),
Number(f64),
/// `[expression]` with [`crate::Options::es2015`]: the key is the expression's value.
Computed(ExprId),
}
impl PropertyKey {
/// The key as the string a property is stored under (a number through ToString).
/// The key as the string a property is stored under (a number through ToString); empty for
/// a computed key, whose string is known only at run time.
pub fn to_utf16(&self) -> Vec<u16> {
match self {
PropertyKey::Ident(name) => name.encode_utf16().collect(),
PropertyKey::String(s) => s.clone(),
PropertyKey::Number(n) => crate::number::to_string(*n).encode_utf16().collect(),
PropertyKey::Computed(_) => Vec::new(),
}
}
}
@@ -100,6 +104,8 @@ pub enum PropertyValue {
Init(ExprId),
Get(FunctionId),
Set(FunctionId),
/// A method (`m() {…}`, ECMA-262 2015 section 14.3).
Method(FunctionId),
}
#[derive(Clone, Debug, PartialEq)]
@@ -109,6 +115,18 @@ pub struct Property {
pub span: Span,
}
impl Property {
/// The property is `__proto__: value`, which sets the new object's prototype (ECMA-262 2015
/// section B.3.1): a data property with a name written out, not computed and not shorthand
/// (`{__proto__}`, whose value starts where the property does).
pub fn is_proto_setter(&self, ast: &Ast) -> bool {
let PropertyValue::Init(value) = self.value else { return false };
ast.expr_span(value).start != self.span.start
&& matches!(self.key, PropertyKey::Ident(_) | PropertyKey::String(_))
&& self.key.to_utf16().into_iter().eq("__proto__".encode_utf16())
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Expr {
This,
@@ -277,20 +295,33 @@ pub enum XmlNamePart {
Computed(ExprId),
}
/// What a declaration, a parameter or a catch clause binds: a name, or with
/// [`crate::Options::es2015`] a destructuring pattern (ECMA-262 11th edition, section 13.3.3).
///
/// A pattern is an [`Expr::Array`] or an [`Expr::Object`] whose targets are [`Expr::Ident`]
/// names or nested patterns; an [`Expr::Assign`] with no operator gives a target its default
/// value, and an [`Expr::Spread`] as the last element of an array pattern is its rest element.
#[derive(Clone, Debug, PartialEq)]
pub enum Binding {
Name(Name),
Pattern(ExprId),
}
#[derive(Clone, Debug, PartialEq)]
pub struct VarDecl {
pub name: Name,
pub target: Binding,
pub init: Option<ExprId>,
}
/// What a `for (… in …)` statement assigns each property name to.
/// What a `for (… in …)` or `for (… of …)` statement assigns each property name or value to.
#[derive(Clone, Debug, PartialEq)]
pub enum ForInTarget {
/// `for (var x in o)`, with the declaration's initializer if it has one.
Var(VarDecl),
/// An assignment target, or with [`crate::Options::es2015`] an assignment pattern.
Expr(ExprId),
/// `for (let x in o)` or `for (const x in o)`: a new binding for each name.
Lexical(LexKind, Name),
Lexical(LexKind, Binding),
}
#[derive(Clone, Debug, PartialEq)]
@@ -312,7 +343,7 @@ pub struct SwitchCase {
#[derive(Clone, Debug, PartialEq)]
pub struct CatchClause {
pub param: Name,
pub param: Binding,
pub body: Vec<StmtId>,
}
@@ -351,6 +382,12 @@ pub enum Stmt {
body: StmtId,
each: bool,
},
/// `for (… of …)` with [`crate::Options::es2015`] (ECMA-262 11th edition, section 13.7.5).
ForOf {
target: ForInTarget,
iterable: ExprId,
body: StmtId,
},
/// `default xml namespace = expression;`.
DefaultXmlNamespace(ExprId),
Continue(Option<Name>),
@@ -385,6 +422,8 @@ pub enum FunctionKind {
Setter,
/// An arrow function; one with an expression body has a body of one `return` statement.
Arrow,
/// A method in an object literal.
Method,
}
#[derive(Clone, Debug, PartialEq)]
@@ -392,11 +431,11 @@ pub struct Function {
pub kind: FunctionKind,
pub name: Option<Name>,
/// The parameters before a rest parameter.
pub params: Vec<Name>,
pub params: Vec<Binding>,
/// Each parameter's default value, in the order of `params` (empty when none has one).
pub defaults: Vec<Option<ExprId>>,
/// The rest parameter (`...name`).
pub rest: Option<Name>,
/// The rest parameter (`...name` or `...[pattern]`).
pub rest: Option<Binding>,
pub body: Vec<StmtId>,
/// The function's code is strict mode code: its own directive prologue holds `"use strict"`,
/// or the code around it is strict.
@@ -405,9 +444,9 @@ pub struct Function {
}
impl Function {
/// The parameters are plain names: no default value and no rest parameter.
/// The parameters are plain names: no pattern, no default value and no rest parameter.
pub fn simple_params(&self) -> bool {
self.rest.is_none() && self.defaults.iter().all(Option::is_none)
self.rest.is_none() && self.defaults.iter().all(Option::is_none) && self.params.iter().all(|p| matches!(p, Binding::Name(_)))
}
}
@@ -440,6 +479,34 @@ impl Ast {
self.functions.get(id.0 as usize)
}
/// The names a binding binds, in source order.
pub fn bound_names(&self, binding: &Binding) -> Vec<Name> {
match binding {
Binding::Name(n) => vec![n.clone()],
Binding::Pattern(p) => self.pattern_names(*p),
}
}
/// The names a destructuring pattern binds, in source order, walked without recursion.
pub fn pattern_names(&self, pattern: ExprId) -> Vec<Name> {
let mut out = Vec::new();
let mut work = vec![pattern];
while let Some(id) = work.pop() {
match self.expr(id) {
Some(Expr::Ident(n)) => out.push(Name { name: n.clone(), span: self.expr_span(id) }),
Some(Expr::Array(elements)) => work.extend(elements.iter().rev().flatten().copied()),
Some(Expr::Object(props)) => work.extend(props.iter().rev().filter_map(|p| match p.value {
PropertyValue::Init(e) => Some(e),
_ => None,
})),
Some(Expr::Assign { target, .. }) => work.push(*target),
Some(Expr::Spread(arg)) => work.push(*arg),
_ => {}
}
}
out
}
/// The expression with any parentheses around it removed.
pub fn unparenthesized(&self, mut id: ExprId) -> ExprId {
while let Some(Expr::Paren(inner)) = self.expr(id) {
+182 -12
View File
@@ -3,7 +3,8 @@
//! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex
//! B's `escape` and `unescape`, and the prototypes primitive values look properties up on, with
//! `Boolean.prototype`'s `toString` and `valueOf`. `String`, `Number`, `RegExp` and `Date` are in
//! their own modules.
//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`) and
//! the iterators of arrays, strings and `arguments` objects (in `iterator`).
//!
//! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object
//! or property it makes is checked against the heap limit before it is made, so no built-in can
@@ -12,16 +13,19 @@
mod array;
pub(crate) mod extensions;
mod global;
pub(crate) mod iterator;
mod json;
mod math;
mod object;
mod symbol;
use std::rc::Rc;
use crate::bytecode::{CodeKind, Source};
use crate::compiler::{CompileFail, compile_constructed_function};
use crate::heap::{
BOUND_ARG_BYTES, Class, Func, HIDDEN, Key, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key, string_bytes,
BOUND_ARG_BYTES, CONFIGURABLE, Class, Func, HIDDEN, Key, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key,
string_bytes,
};
use crate::interp::{Abrupt, Desc, ErrorType, Interp, JsResult};
use crate::value::{Str, Value, index_key, number_to_str, to_uint32};
@@ -32,9 +36,30 @@ fn alloc(interp: &mut Interp, class: Class, proto: Option<ObjId>) -> ObjId {
/// A built-in function object.
pub(crate) fn native(interp: &mut Interp, name: &'static str, f: NativeFn, length: u32, kind: NativeKind, constructor: bool) -> JsResult<ObjId> {
native_with_prefix(interp, "", name, f, length, kind, constructor)
}
/// The function of a built-in accessor `name`: `prefix` is `get ` for its getter and `set ` for
/// its setter.
pub(crate) fn accessor_native(interp: &mut Interp, prefix: &'static str, name: &'static str, f: NativeFn, length: u32) -> JsResult<ObjId> {
native_with_prefix(interp, prefix, name, f, length, NativeKind::Plain, false)
}
fn native_with_prefix(
interp: &mut Interp,
prefix: &'static str,
name: &'static str,
f: NativeFn,
length: u32,
kind: NativeKind,
constructor: bool,
) -> JsResult<ObjId> {
let proto = interp.intrinsics.function_proto;
let o = alloc(interp, Class::Function(Func::Native { f, kind, constructor, name }), Some(proto));
let o = alloc(interp, Class::Function(Func::Native { f, kind, constructor, name, prefix }), Some(proto));
interp.define(o, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?;
if interp.builtin_names {
es2015_native(interp, o, Some(&format!("{prefix}{name}")))?;
}
Ok(o)
}
@@ -44,9 +69,97 @@ pub(crate) fn pausable_method(interp: &mut Interp, on: ObjId, name: &'static str
let proto = interp.intrinsics.function_proto;
let m = alloc(interp, Class::Function(Func::Pausable { f, name }), Some(proto));
interp.define(m, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?;
if interp.builtin_names {
es2015_native(interp, m, Some(name))?;
}
interp.define(on, key(name), Prop::Data { value: Value::Object(m), flags: HIDDEN })
}
/// Gives the built-in functions the `name` and `length` of ECMA-262 2015 section 17: each one's
/// `length` becomes configurable, and it gets a `name` that is not writable, not enumerable and
/// configurable: the name it is installed under, with `get ` or `set ` before it for an accessor's
/// function, and `""` for `Function.prototype`. A realm does this once, at the start of its first
/// run with [`crate::Options::es2015`], under the limits set for that run; [`native`] and
/// [`pausable_method`] do it for the functions made after that. The bytes of the new properties
/// are checked against the heap limit first: when they do not fit, nothing changes and the error
/// is returned, and the next run with the option tries again.
pub(crate) fn es2015_names(interp: &mut Interp) -> JsResult<()> {
if interp.builtin_names {
return Ok(());
}
// Functions no script can reach any more are collected first, so the plan names only the
// ones that stay.
interp.collect_garbage();
let plan = es2015_name_plan(interp);
let bytes = plan
.iter()
.filter_map(|(_, name)| name.as_ref())
.map(|name| PROP_BYTES + string_bytes("name".len()) + string_bytes(name.len()))
.sum::<usize>();
interp.reserve_heap(bytes)?;
let thrower = interp.intrinsics.throw_type_error;
for (id, name) in plan {
// A function the reservation's collection freed needs no name.
if interp.heap.object(id).is_none() {
continue;
}
if id == thrower {
// %ThrowTypeError% keeps its fixed `length`, and its `name` is fixed too (ECMA-262
// 2020 section 9.2.9.1).
if name.is_some() {
interp.define(id, key("name"), Prop::Data { value: Value::str(""), flags: 0 })?;
}
} else {
es2015_native(interp, id, name.as_deref())?;
}
}
interp.builtin_names = true;
Ok(())
}
/// The built-in functions, each with the `name` [`es2015_names`] gives it, or `None` when it has
/// one already (a script may have defined it).
fn es2015_name_plan(interp: &Interp) -> Vec<(ObjId, Option<String>)> {
let thrower = interp.intrinsics.throw_type_error;
let mut plan = Vec::new();
for id in interp.heap.object_ids() {
let Some(o) = interp.heap.object(id) else { continue };
// A function a script made non-extensible (frozen, sealed or locked) keeps its properties
// as they are.
if !o.extensible && id != thrower {
continue;
}
let name = match &o.class {
_ if id == thrower => String::new(),
Class::Function(Func::Native { name, prefix, .. }) => format!("{prefix}{name}"),
Class::Function(Func::Pausable { name, .. }) => (*name).to_string(),
_ => continue,
};
plan.push((id, (!o.props.contains(&key("name"))).then_some(name)));
}
plan
}
/// Makes built-in function `f`'s `length` configurable and gives it the `name` `name`, when there
/// is one, unless it has a `name` already. A function that is not extensible keeps its properties
/// as they are. The new property's bytes are checked against the heap limit first, with `f` held
/// as a root.
fn es2015_native(interp: &mut Interp, f: ObjId, name: Option<&str>) -> JsResult<()> {
if !interp.object_mut(f)?.extensible {
return Ok(());
}
if let Some(Prop::Data { flags, .. }) = interp.object_mut(f)?.props.get_mut(&key("length")) {
*flags |= CONFIGURABLE;
}
let Some(name) = name.filter(|_| !interp.heap.object(f).is_some_and(|o| o.props.contains(&key("name")))) else { return Ok(()) };
interp.rooted(&[Value::Object(f)], |i| i.reserve_heap(PROP_BYTES + string_bytes("name".len()) + string_bytes(name.len())))?;
let o = interp.object_mut(f)?;
// `name` comes right after `length`, as the built-ins list them.
o.props.insert_after(&key("length"), key("name"), Prop::Data { value: Value::str(name), flags: CONFIGURABLE });
interp.heap.bytes = interp.heap.bytes.saturating_add(PROP_BYTES + string_bytes("name".len()) + string_bytes(name.len()));
Ok(())
}
pub(crate) fn method(interp: &mut Interp, on: ObjId, name: &'static str, f: NativeFn, length: u32) -> JsResult<()> {
let m = native(interp, name, f, length, NativeKind::Plain, false)?;
interp.define(on, key(name), Prop::Data { value: Value::Object(m), flags: HIDDEN })
@@ -83,7 +196,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> {
interp.intrinsics.object_proto = object_proto;
let function_proto = alloc(
interp,
Class::Function(Func::Native { f: function_proto_call, kind: NativeKind::Plain, constructor: false, name: "" }),
Class::Function(Func::Native { f: function_proto_call, kind: NativeKind::Plain, constructor: false, name: "", prefix: "" }),
Some(object_proto),
);
interp.intrinsics.function_proto = function_proto;
@@ -142,6 +255,10 @@ fn try_install(interp: &mut Interp) -> JsResult<()> {
crate::number_builtins::install(interp)?;
crate::regexp_builtins::install(interp)?;
crate::date_builtins::install(interp)?;
if interp.options.es2015 {
symbol::install(interp, object)?;
iterator::install(interp)?;
}
if interp.options.e4x {
crate::xml_builtins::install(interp)?;
}
@@ -370,7 +487,9 @@ fn object_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResu
interp.to_object(&v).map(Value::Object)
}
/// `Object.prototype.toString` (section 15.2.4.2).
/// `Object.prototype.toString` (section 15.2.4.2). In a run with [`crate::Options::es2015`], a
/// string `@@toStringTag` takes the place of the class name (ECMA-262 11th edition, section
/// 19.1.3.6).
fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
// With `$.localize` on, a localization object gives its text for the current locale.
if interp.localization.enabled()
@@ -384,6 +503,13 @@ fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J
Value::Null => "Null",
_ => {
let o = interp.to_object(&this)?;
// The tag's getter can run script that collects, and the object of a primitive is
// reachable from nowhere else.
let tag = interp.rooted(&[Value::Object(o)], |i| i.string_tag_of(o))?;
if let Some(tag) = tag {
let roots = [Value::String(tag.clone())];
return interp.rooted(&roots, |i| i.wrap_str("[object ", Some(&tag), "]"));
}
interp.heap.object(o).map_or("Object", |o| o.class.name())
}
};
@@ -431,9 +557,9 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js
}
fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let k = interp.to_key(&arg(args, 0))?;
let k = interp.to_prop_key(&arg(args, 0))?;
let o = interp.to_object(&this)?;
Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some()))
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some()))
}
fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
@@ -450,9 +576,9 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) ->
}
fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let k = interp.to_key(&arg(args, 0))?;
let k = interp.to_prop_key(&arg(args, 0))?;
let o = interp.to_object(&this)?;
Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable())))
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable())))
}
// ---- Function ----
@@ -538,15 +664,21 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J
let bound_this = arg(args, 0);
let bound_args: Rc<[Value]> = args.get(1..).unwrap_or_default().into();
// A host function's `length` is an ordinary property a script can set, so it is converted
// to an integer first, as later editions specify.
let target_length = match interp.get_from(target, &key("length"), &this)? {
// to an integer first, as later editions specify. With ECMAScript 2015 only an own `length` is
// read (ECMA-262 2020 section 19.2.3.2 step 4), so an inherited getter does not run.
let has_length = !interp.options.es2015 || interp.get_own_property(target, &key("length"))?.is_some();
let length_value = if has_length { interp.get_from(target, &key("length"), &this)? } else { Value::Undefined };
let target_length = match length_value {
Value::Number(n) if n.is_nan() => 0.0,
Value::Number(n) => n.trunc(),
_ => 0.0,
};
// Adding 0 turns a negative zero into 0.
let length = (target_length - bound_args.len() as f64).max(0.0) + 0.0;
interp.reserve_heap(OBJECT_BYTES + 4 * PROP_BYTES + BOUND_ARG_BYTES * bound_args.len())?;
if interp.options.es2015 {
return bind_es2015(interp, target, bound_this, bound_args, length);
}
interp.reserve_heap(OBJECT_BYTES + prop_bytes(&["length", "caller", "arguments"]) + BOUND_ARG_BYTES * bound_args.len())?;
let proto = interp.intrinsics.function_proto;
let class = Class::Function(Func::Bound { target, this: bound_this, args: bound_args.clone() });
let f = interp.heap.alloc_object(Object::new(class, Some(proto)));
@@ -559,6 +691,44 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J
Ok(Value::Object(f))
}
/// The bytes [`Interp::define`] counts for new properties with these names.
fn prop_bytes(names: &[&str]) -> usize {
names.iter().map(|n| PROP_BYTES + string_bytes(n.len())).sum()
}
/// The rest of `Function.prototype.bind` with [`crate::Options::es2015`] (ECMA-262 2020 section
/// 19.2.3.2): the bound function's `length` is configurable, its `name` is `bound ` and the
/// target's `name` when that is a string (read after `length`, so a getter for it runs). It keeps
/// the `caller` and `arguments` that throw, as without the option.
fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult<Value> {
let target_name = match interp.get_from(target, &key("name"), &Value::Object(target))? {
Value::String(s) => s,
_ => Str::from(""),
};
let name_len = "bound ".len().saturating_add(target_name.len());
// A rope name is flattened first, with the copy's bytes reserved and its units charged as fuel.
let target_units = crate::string_builtins::flat_charged(interp, &target_name)?;
interp.rooted(&[Value::String(target_name.clone())], |i| {
i.reserve_heap(
OBJECT_BYTES + prop_bytes(&["length", "name", "caller", "arguments"]) + BOUND_ARG_BYTES * bound_args.len() + string_bytes(name_len),
)
})?;
crate::string_builtins::charge_units(interp, name_len)?;
let mut units: Vec<u16> = "bound ".encode_utf16().collect();
units.extend_from_slice(&target_units);
let proto = interp.intrinsics.function_proto;
let class = Class::Function(Func::Bound { target, this: bound_this, args: bound_args.clone() });
let f = interp.heap.alloc_object(Object::new(class, Some(proto)));
interp.heap.bytes = interp.heap.bytes.saturating_add(BOUND_ARG_BYTES * bound_args.len() + string_bytes(name_len));
interp.define(f, key("length"), Prop::Data { value: Value::Number(length), flags: CONFIGURABLE })?;
interp.define(f, key("name"), Prop::Data { value: Value::String(Str::from_units(units)), flags: CONFIGURABLE })?;
let thrower = Some(interp.intrinsics.throw_type_error);
for name in ["caller", "arguments"] {
interp.define(f, key(name), Prop::Accessor { get: thrower, set: thrower, flags: 0 })?;
}
Ok(Value::Object(f))
}
/// The global `eval` called indirectly (section 15.1.2.1.1): global code in the global
/// environment.
fn eval(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
+7 -1
View File
@@ -235,6 +235,7 @@ impl Source {
}
Value::String(s) => self.quoted(interp, &s.flat()),
Value::Object(id) => self.object(interp, *id),
Value::Symbol(_) => Err(interp.type_error("toSource: a Symbol cannot be written as source")),
}
}
@@ -280,13 +281,18 @@ impl Source {
// only, so an array with other properties, an object with another prototype and a property
// that is not enumerable are refused.
let enumerable = o.props.iter().all(|(_, p)| p.enumerable());
let has_symbols = o.syms.as_ref().is_some_and(|m| m.len() > 0);
let shape = match &o.class {
Class::Array { length, .. }
if o.proto == Some(array_proto) && enumerable && o.props.iter().all(|(k, _)| array_index(k).is_some_and(|i| i < *length)) =>
if o.proto == Some(array_proto)
&& enumerable
&& !has_symbols
&& o.props.iter().all(|(k, _)| array_index(k).is_some_and(|i| i < *length)) =>
{
Some(Err(*length))
}
Class::Array { .. } => return Err(interp.type_error(NOT_PLAIN_ARRAY)),
Class::Ordinary if has_symbols => return Err(interp.type_error("toSource: an object with a Symbol property cannot be written as source")),
Class::Ordinary if o.proto == Some(object_proto) && enumerable => {
Some(Ok(o.props.iter().map(|(k, p)| (k.clone(), p.clone())).collect::<Vec<_>>()))
}
+230
View File
@@ -0,0 +1,230 @@
//! The iterators of arrays, strings and `arguments` objects (ECMA-262 11th edition,
//! <https://262.ecma-international.org/11.0/>): `%IteratorPrototype%` (section 25.1.2),
//! `%ArrayIteratorPrototype%` with `Array.prototype.values`, `keys`, `entries` and `@@iterator`
//! (sections 22.1.3 and 22.1.5), `%StringIteratorPrototype%` with `String.prototype[@@iterator]`
//! (sections 21.1.3.29 and 21.1.5), which steps by code point, and the `@@iterator` of every
//! `arguments` object (section 9.4.4). Installed in a realm with [`crate::Options::es2015`] only.
//!
//! An iterator's `next` takes a unit of fuel for each step. An Array Iterator reads its object's
//! `length` at every step, so elements added while it runs are visited, and it lets go of the
//! object once it is done.
use super::{create_at, data, native, new_array, new_string};
use crate::heap::{CONFIGURABLE, Class, HIDDEN, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key, string_bytes};
use crate::interp::{Interp, JsResult};
use crate::value::{Str, Value, number_to_str};
/// What an Array Iterator gives at each step (section 22.1.5.1).
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum ArrayKind {
Keys,
Values,
Entries,
}
/// An iterator's state. The object or string is `None` once the iterator is done.
#[derive(Clone)]
pub(crate) enum IterState {
/// [[IteratedObject]], [[ArrayIteratorNextIndex]] and [[ArrayIterationKind]].
Array { target: Option<ObjId>, next: f64, kind: ArrayKind },
/// [[IteratedString]], flat, and [[StringIteratorNextIndex]] in code units.
String { text: Option<Str>, pos: usize },
}
pub(super) fn install(interp: &mut Interp) -> JsResult<()> {
let Some(wk) = interp.symbols.well_known.as_ref() else { return Ok(()) };
let (iterator, to_string_tag) = (wk.iterator.clone(), wk.to_string_tag.clone());
let Some(mut objects) = interp.symbols.objects else { return Ok(()) };
let object_proto = interp.intrinsics.object_proto;
let iterator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto)));
super::symbol::sym_method(interp, iterator_proto, iterator.clone(), "[Symbol.iterator]", return_this, 0, HIDDEN)?;
let array_iterator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(iterator_proto)));
super::method(interp, array_iterator_proto, "next", array_iterator_next, 0)?;
interp.define_sym(array_iterator_proto, to_string_tag.clone(), Prop::Data { value: Value::str("Array Iterator"), flags: CONFIGURABLE })?;
let string_iterator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(iterator_proto)));
super::method(interp, string_iterator_proto, "next", string_iterator_next, 0)?;
interp.define_sym(string_iterator_proto, to_string_tag, Prop::Data { value: Value::str("String Iterator"), flags: CONFIGURABLE })?;
let array_proto = interp.intrinsics.array_proto;
let values = native(interp, "values", array_values, 0, crate::heap::NativeKind::Plain, false)?;
data(interp, array_proto, "values", Value::Object(values), HIDDEN)?;
interp.define_sym(array_proto, iterator.clone(), Prop::Data { value: Value::Object(values), flags: HIDDEN })?;
super::method(interp, array_proto, "keys", array_keys, 0)?;
super::method(interp, array_proto, "entries", array_entries, 0)?;
let string_proto = interp.intrinsics.string_proto;
super::symbol::sym_method(interp, string_proto, iterator, "[Symbol.iterator]", string_iterator, 0, HIDDEN)?;
objects.array_iterator_proto = array_iterator_proto;
objects.string_iterator_proto = string_iterator_proto;
objects.array_values = values;
interp.symbols.objects = Some(objects);
Ok(())
}
/// Gives a new `arguments` object its `@@iterator`, `%ArrayProto_values%` (section 9.4.4.6,
/// step 20, and section 9.4.4.7, step 7), in a realm that has it.
pub(crate) fn define_arguments_iterator(interp: &mut Interp, a: ObjId) -> JsResult<()> {
let (Some(objects), Some(sym)) = (interp.symbols.objects, interp.well_known(|w| &w.iterator)) else { return Ok(()) };
interp.define_sym(a, sym, Prop::Data { value: Value::Object(objects.array_values), flags: HIDDEN })
}
/// `%IteratorPrototype%[@@iterator]()` (section 25.1.2.1): the iterator itself.
fn return_this(_: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
Ok(this)
}
/// The bytes of an iterator result: the object and its `value` and `done` properties with their
/// keys, as [`Interp::define`] counts them.
fn iter_result_bytes() -> usize {
OBJECT_BYTES + 2 * PROP_BYTES + string_bytes("value".len()) + string_bytes("done".len())
}
/// CreateIterResultObject (section 7.4.7): `{ value, done }`.
fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult<Value> {
interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(iter_result_bytes()))?;
let proto = interp.intrinsics.object_proto;
let o = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto)));
interp.define(o, key("value"), Prop::Data { value, flags: OPEN })?;
interp.define(o, key("done"), Prop::Data { value: Value::Bool(done), flags: OPEN })?;
Ok(Value::Object(o))
}
/// A new iterator object with `state`, its target kept reachable while it is made.
fn new_iterator(interp: &mut Interp, proto: ObjId, state: IterState, root: Value) -> JsResult<Value> {
interp.rooted(&[root], |i| i.reserve_heap(OBJECT_BYTES))?;
Ok(Value::Object(interp.heap.alloc_object(Object::new(Class::Iterator(Box::new(state)), Some(proto)))))
}
/// CreateArrayIterator (section 22.1.5.1) for `ToObject(this)`.
fn create_array_iterator(interp: &mut Interp, this: &Value, kind: ArrayKind) -> JsResult<Value> {
let o = interp.to_object(this)?;
let Some(proto) = interp.symbols.objects.map(|o| o.array_iterator_proto) else { return Ok(Value::Undefined) };
new_iterator(interp, proto, IterState::Array { target: Some(o), next: 0.0, kind }, Value::Object(o))
}
/// `Array.prototype.values()` (section 22.1.3.32), which is also `Array.prototype[@@iterator]`.
fn array_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
create_array_iterator(interp, &this, ArrayKind::Values)
}
/// `Array.prototype.keys()` (section 22.1.3.16).
fn array_keys(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
create_array_iterator(interp, &this, ArrayKind::Keys)
}
/// `Array.prototype.entries()` (section 22.1.3.4).
fn array_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
create_array_iterator(interp, &this, ArrayKind::Entries)
}
/// `String.prototype[@@iterator]()` (section 21.1.3.29).
fn string_iterator(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
if this.is_nullish() {
return Err(interp.type_error("String.prototype[Symbol.iterator] was called on null or undefined"));
}
let s = interp.to_str(&this)?;
let flat = Str::from_rc(crate::string_builtins::flat_charged(interp, &s)?);
let Some(proto) = interp.symbols.objects.map(|o| o.string_iterator_proto) else { return Ok(Value::Undefined) };
let root = Value::String(flat.clone());
new_iterator(interp, proto, IterState::String { text: Some(flat), pos: 0 }, root)
}
/// The state of the iterator `this`, or a `TypeError` naming `what` when `this` is not one.
fn state_of<'a>(interp: &'a mut Interp, this: &Value, string: bool, what: &str) -> JsResult<&'a mut IterState> {
let ok = match this {
Value::Object(o) => match interp.heap.object(*o).map(|x| &x.class) {
Some(Class::Iterator(s)) => matches!(**s, IterState::String { .. }) == string,
_ => false,
},
_ => false,
};
if !ok {
return Err(interp.type_error(&format!("{what}.next was called on a value that is not an {what}")));
}
match this.as_object().and_then(|o| interp.heap.object_mut(o)).map(|x| &mut x.class) {
Some(Class::Iterator(s)) => Ok(s),
_ => Err(crate::interp::Abrupt::Internal("iterator state went missing".into())),
}
}
/// ToLength (section 7.1.20).
fn to_length(interp: &mut Interp, v: &Value) -> JsResult<f64> {
let n = interp.to_number(v)?;
if n.is_nan() || n <= 0.0 {
return Ok(0.0);
}
Ok(n.trunc().min(9_007_199_254_740_991.0))
}
/// `%ArrayIteratorPrototype%.next()` (section 22.1.5.2.1).
fn array_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
let IterState::Array { target, next, kind } = *state_of(interp, &this, false, "Array Iterator")? else {
return Err(crate::interp::Abrupt::Internal("not an Array Iterator".into()));
};
interp.use_fuel()?;
let Some(a) = target else { return iter_result(interp, Value::Undefined, true) };
// Reading `length` and the element can run script that collects, and that script can finish
// the iterator, which then no longer holds the object.
let roots = [this.clone(), Value::Object(a)];
interp.rooted(&roots, |interp| array_step(interp, &this, a, next, kind))
}
/// One step of an Array Iterator over `a` at index `next`, with `this` and `a` kept reachable.
fn array_step(interp: &mut Interp, this: &Value, a: ObjId, next: f64, kind: ArrayKind) -> JsResult<Value> {
let len = interp.get_from(a, &key("length"), &Value::Object(a))?;
let len = to_length(interp, &len)?;
if next >= len {
if let IterState::Array { target, .. } = state_of(interp, this, false, "Array Iterator")? {
*target = None;
}
return iter_result(interp, Value::Undefined, true);
}
if let IterState::Array { next: n, .. } = state_of(interp, this, false, "Array Iterator")? {
*n = next + 1.0;
}
let index = Value::Number(next);
let value = match kind {
ArrayKind::Keys => index,
ArrayKind::Values | ArrayKind::Entries => {
let k = number_to_str(next).flat();
let v = interp.get_from(a, &k, &Value::Object(a))?;
if kind == ArrayKind::Values {
v
} else {
let pair = interp.rooted(std::slice::from_ref(&v), |i| new_array(i, 0))?;
interp.rooted(&[Value::Object(pair), v.clone()], |i| {
create_at(i, pair, 0.0, index)?;
create_at(i, pair, 1.0, v.clone())
})?;
Value::Object(pair)
}
}
};
iter_result(interp, value, false)
}
/// `%StringIteratorPrototype%.next()` (section 21.1.5.2.1): the next code point, a surrogate
/// pair kept together and a lone surrogate given alone.
fn string_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
interp.use_fuel()?;
let state = state_of(interp, &this, true, "String Iterator")?;
let IterState::String { text, pos } = state else { return Err(crate::interp::Abrupt::Internal("not a String Iterator".into())) };
let Some(s) = text.as_ref() else { return iter_result(interp, Value::Undefined, true) };
let units = s.flat();
let Some(&first) = units.get(*pos) else {
*text = None;
return iter_result(interp, Value::Undefined, true);
};
let pair = (0xD800..0xDC00).contains(&first) && units.get(*pos + 1).is_some_and(|u| (0xDC00..0xE000).contains(u));
let width = if pair { 2 } else { 1 };
let piece = units.get(*pos..*pos + width).map(<[u16]>::to_vec).unwrap_or_default();
*pos += width;
interp.rooted(std::slice::from_ref(&this), |interp| {
let v = new_string(interp, piece)?;
iter_result(interp, v, false)
})
}
+11 -31
View File
@@ -556,7 +556,7 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K
}
}
Ok(match v {
Value::Undefined => Item::Skip,
Value::Undefined | Value::Symbol(_) => Item::Skip,
Value::Object(_) if interp.is_callable(&v) => Item::Skip,
Value::Object(o) => Item::Container(o),
other => Item::Primitive(other),
@@ -565,39 +565,19 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K
/// ToNumber of a Number object, or ToString of a String object (of either when `as_string` is
/// set), as section 15.12.3 applies them in Str step 4, step 4.b.ii and step 5. Returns `None`
/// for any other value. When the method that [[DefaultValue]] (section 8.12.8) calls first is not
/// found on the object or on its prototype chain before the object's standard prototype, the
/// result is the object's [[PrimitiveValue]] (sections 8.6.2 and 9.9), the value that
/// `Number.prototype.valueOf` (15.7.4.4), `Number.prototype.toString` (15.7.4.2) and
/// `String.prototype.toString` (15.5.4.2) return. Otherwise ToPrimitive calls the method found.
/// for any other value. The conversion is ToPrimitive (section 9.1) with the Number or String
/// hint, so `valueOf` and `toString` are looked up along the object's whole prototype chain, and
/// in a realm with [`crate::Options::es2015`] an `@@toPrimitive` method on the object is called
/// first (ECMA-262 11th edition, section 7.1.1).
fn unwrap_primitive(interp: &mut Interp, v: &Value, as_string: bool) -> JsResult<Option<Value>> {
let Value::Object(o) = v else { return Ok(None) };
let (primitive, proto, string) = match interp.heap.object(*o).map(|x| &x.class) {
Some(Class::Number(n)) => (Value::Number(*n), interp.intrinsics.number_proto, as_string),
Some(Class::String(s)) => (Value::String(s.clone()), interp.intrinsics.string_proto, true),
let string = match interp.heap.object(*o).map(|x| &x.class) {
Some(Class::Number(_)) => as_string,
Some(Class::String(_)) => true,
_ => return Ok(None),
};
let (hint, name) = if string { (Hint::String, "toString") } else { (Hint::Number, "valueOf") };
let p = if reaches_prototype(interp, *o, proto, name)? { primitive } else { interp.to_primitive(v, hint)? };
Ok(Some(if string { Value::String(interp.primitive_to_str(&p)) } else { Value::Number(interp.to_number(&p)?) }))
}
/// Whether looking up `name` from `o` reaches the object `proto` on the prototype chain before
/// any object on the way, `proto` included, has its own property `name`.
fn reaches_prototype(interp: &mut Interp, o: ObjId, proto: ObjId, name: &str) -> JsResult<bool> {
let k = key(name);
let mut cur = Some(o);
while let Some(id) = cur {
interp.use_fuel()?;
if interp.get_own_property(id, &k)?.is_some() {
return Ok(false);
}
if id == proto {
return Ok(true);
}
cur = interp.heap.object(id).and_then(|x| x.proto);
}
Ok(false)
let p = interp.to_primitive(v, if string { Hint::String } else { Hint::Number })?;
Ok(Some(if string { Value::String(interp.to_str(&p)?) } else { Value::Number(interp.to_number(&p)?) }))
}
/// Quote (section 15.12.3): the string in double quotes with the characters JSON escapes.
@@ -637,7 +617,7 @@ fn write_primitive(interp: &mut Interp, out: &mut Builder, v: &Value) -> JsResul
let units = flat_charged(i, s)?;
write_quoted(i, out, &units)
}),
Value::Undefined | Value::Object(_) => Ok(()),
Value::Undefined | Value::Object(_) | Value::Symbol(_) => Ok(()),
}
}
+30 -13
View File
@@ -7,6 +7,7 @@
use super::{ELEMENT_BYTES, arg, create_at, method, new_array};
use crate::heap::{CONFIGURABLE, ENUMERABLE, Key, OBJECT_BYTES, OPEN, ObjId, Object, Prop, WRITABLE, key};
use crate::interp::{Desc, Interp, JsResult};
use crate::symbol::PropKey;
use crate::value::{Str, Value};
pub(super) fn install(interp: &mut Interp, object: ObjId) -> JsResult<()> {
@@ -119,6 +120,14 @@ fn names_array(interp: &mut Interp, names: Vec<Key>) -> JsResult<Value> {
})
}
/// The object's own property keys: its names, then its Symbols (ECMA-262 11th edition, section
/// 9.1.11).
fn own_prop_keys(interp: &mut Interp, o: ObjId) -> JsResult<Vec<PropKey>> {
let mut keys: Vec<PropKey> = interp.own_keys(o)?.into_iter().map(PropKey::Str).collect();
keys.extend(interp.own_symbols(o)?.into_iter().map(PropKey::Sym));
Ok(keys)
}
/// `Object.getPrototypeOf` (section 15.2.3.2).
fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
let o = interp.to_object(&arg(args, 0))?;
@@ -129,8 +138,8 @@ fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> J
fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
let o = interp.to_object(&arg(args, 0))?;
interp.rooted(&[Value::Object(o)], |interp| {
let k = interp.to_key(&arg(args, 1))?;
match interp.get_own_property(o, &k)? {
let k = interp.to_prop_key(&arg(args, 1))?;
match interp.get_own_pk(o, &k)? {
Some(p) => from_prop(interp, &p),
None => Ok(Value::Undefined),
}
@@ -166,10 +175,10 @@ fn create(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Va
/// `Object.defineProperty` (section 15.2.3.6).
fn define_property(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
let o = require_object(interp, &arg(args, 0), "defineProperty")?;
interp.with_key(&arg(args, 1), |interp, k| {
interp.with_prop_key(&arg(args, 1), |interp, k| {
let desc = to_desc(interp, &arg(args, 2))?;
let roots = desc_values(&desc);
interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, true))
interp.rooted(&roots, |interp| interp.define_own_pk(o, k, &desc, true))
})?;
Ok(Value::Object(o))
}
@@ -189,12 +198,20 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> {
interp.temp_roots.push(Value::Object(p));
let r = (|| {
let mut descs = Vec::new();
for k in interp.own_keys(p)? {
let keys = own_prop_keys(interp, p)?;
// A getter can delete a Symbol-keyed property already read, so the Symbols stay rooted
// until they are defined on `o`.
for k in &keys {
if let PropKey::Sym(s) = k {
interp.temp_roots.push(Value::Symbol(s.clone()));
}
}
for k in keys {
interp.use_fuel()?;
if !interp.get_own_property(p, &k)?.is_some_and(|prop| prop.enumerable()) {
if !interp.get_own_pk(p, &k)?.is_some_and(|prop| prop.enumerable()) {
continue;
}
let v = interp.get_from(p, &k, &Value::Object(p))?;
let v = interp.get_value_pk(&Value::Object(p), &k)?;
interp.temp_roots.push(v.clone());
let desc = to_desc(interp, &v)?;
interp.temp_roots.extend(desc_values(&desc));
@@ -202,7 +219,7 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> {
}
for (k, desc) in descs {
interp.use_fuel()?;
interp.define_own_property(o, k, &desc, true)?;
interp.define_own_pk(o, k, &desc, true)?;
}
Ok(())
})();
@@ -214,9 +231,9 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> {
/// then makes the object non-extensible (sections 15.2.3.8 and 15.2.3.9).
fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult<Value> {
let Value::Object(o) = v else { return Ok(v) };
for k in interp.own_keys(o)? {
for k in own_prop_keys(interp, o)? {
interp.use_fuel()?;
let Some(prop) = interp.get_own_property(o, &k)? else { continue };
let Some(prop) = interp.get_own_pk(o, &k)? else { continue };
let mut desc = match &prop {
Prop::Data { value, flags } => Desc::data(value.clone(), *flags),
Prop::Accessor { get, set, flags } => Desc {
@@ -231,7 +248,7 @@ fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult<Value> {
if freeze && desc.is_data() {
desc.writable = Some(false);
}
interp.define_own_property(o, k, &desc, true)?;
interp.define_own_pk(o, k, &desc, true)?;
}
if let Some(obj) = interp.heap.object_mut(o) {
obj.extensible = false;
@@ -263,9 +280,9 @@ fn prevent_extensions(interp: &mut Interp, _: Value, args: &[Value], _: bool) ->
fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult<Value> {
let Value::Object(o) = v else { return Ok(Value::Bool(true)) };
let o = *o;
for k in interp.own_keys(o)? {
for k in own_prop_keys(interp, o)? {
interp.use_fuel()?;
let Some(prop) = interp.get_own_property(o, &k)? else { continue };
let Some(prop) = interp.get_own_pk(o, &k)? else { continue };
if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) {
return Ok(Value::Bool(false));
}
+183
View File
@@ -0,0 +1,183 @@
//! `Symbol` (ECMA-262 11th edition, section 19.4, <https://262.ecma-international.org/11.0/>):
//! the constructor with `Symbol.for`, `Symbol.keyFor` and the well-known Symbols, the methods of
//! `Symbol.prototype`, `Object.getOwnPropertySymbols` (section 19.1.2.10),
//! `Function.prototype[@@hasInstance]` (section 19.2.3.6) and `Date.prototype[@@toPrimitive]`
//! (section 20.4.4.45). Installed in a realm with [`crate::Options::es2015`] only.
use super::{arg, constructor, create_at, data, method, native, new_array};
use crate::heap::{CONFIGURABLE, Class, NativeFn, NativeKind, ObjId, Object, Prop, SYMBOL_BYTES, string_bytes};
use crate::interp::{Hint, Interp, JsResult};
use crate::symbol::{Es2015Objects, REGISTRY_ENTRY_BYTES, Sym, WellKnown};
use crate::value::{Str, Value};
pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> {
let well_known = WellKnown::new();
let names = [
("iterator", well_known.iterator.clone()),
("asyncIterator", well_known.async_iterator.clone()),
("hasInstance", well_known.has_instance.clone()),
("toPrimitive", well_known.to_primitive.clone()),
("toStringTag", well_known.to_string_tag.clone()),
];
let (to_string_tag, to_primitive, has_instance) =
(well_known.to_string_tag.clone(), well_known.to_primitive.clone(), well_known.has_instance.clone());
interp.symbols.well_known = Some(well_known);
let object_proto = interp.intrinsics.object_proto;
let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto)));
let ctor = native(interp, "Symbol", symbol_ctor, 0, NativeKind::Plain, true)?;
constructor(interp, "Symbol", ctor, proto)?;
method(interp, ctor, "for", symbol_for, 1)?;
method(interp, ctor, "keyFor", key_for, 1)?;
for (name, sym) in names {
data(interp, ctor, name, Value::Symbol(sym), 0)?;
}
method(interp, proto, "toString", to_string, 0)?;
method(interp, proto, "valueOf", value_of, 0)?;
let getter = native(interp, "get description", description, 0, NativeKind::Plain, false)?;
interp.define(proto, crate::heap::key("description"), Prop::Accessor { get: Some(getter), set: None, flags: CONFIGURABLE })?;
interp.define_sym(proto, to_string_tag, Prop::Data { value: Value::str("Symbol"), flags: CONFIGURABLE })?;
sym_method(interp, proto, to_primitive.clone(), "[Symbol.toPrimitive]", symbol_to_primitive, 1, CONFIGURABLE)?;
let date_proto = interp.intrinsics.date_proto;
sym_method(interp, date_proto, to_primitive, "[Symbol.toPrimitive]", date_to_primitive, 1, CONFIGURABLE)?;
method(interp, object_ctor, "getOwnPropertySymbols", get_own_property_symbols, 1)?;
let function_proto = interp.intrinsics.function_proto;
let has_instance = sym_method(interp, function_proto, has_instance, "[Symbol.hasInstance]", function_has_instance, 1, 0)?;
// The iterator prototypes and `%ArrayProto_values%` are set when the iterators are installed.
interp.symbols.objects = Some(Es2015Objects {
symbol_proto: proto,
array_iterator_proto: proto,
string_iterator_proto: proto,
array_values: has_instance,
has_instance,
});
Ok(())
}
/// Defines a built-in function as the property `sym` of `on`, with the attribute `flags`.
pub(super) fn sym_method(interp: &mut Interp, on: ObjId, sym: Sym, name: &'static str, f: NativeFn, length: u32, flags: u8) -> JsResult<ObjId> {
let m = native(interp, name, f, length, NativeKind::Plain, false)?;
interp.define_sym(on, sym, Prop::Data { value: Value::Object(m), flags })?;
Ok(m)
}
/// A new Symbol, its bytes checked against the heap limit and charged to the heap.
fn new_symbol(interp: &mut Interp, description: Option<Str>, registered: bool, extra: usize) -> JsResult<Sym> {
let bytes = SYMBOL_BYTES.saturating_add(extra);
let roots: Vec<Value> = description.iter().cloned().map(Value::String).collect();
interp.rooted(&roots, |i| i.reserve_heap(bytes))?;
interp.heap.bytes = interp.heap.bytes.saturating_add(bytes);
Ok(Sym::new(description, registered))
}
/// `Symbol([description])` (section 19.4.1.1). `new Symbol()` throws a `TypeError`.
fn symbol_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult<Value> {
if construct {
return Err(interp.type_error("the value is not a constructor"));
}
let description = match arg(args, 0) {
Value::Undefined => None,
d => Some(interp.to_str(&d)?),
};
new_symbol(interp, description, false, 0).map(Value::Symbol)
}
/// `Symbol.for(key)` (section 19.4.2.2): the registry's Symbol for the key, made the first time.
fn symbol_for(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
let key = interp.to_str(&arg(args, 0))?;
let units = crate::string_builtins::flat_charged(interp, &key)?;
if let Some(v) = interp.symbols.registry.get(&*units) {
return Ok(v.clone());
}
let extra = REGISTRY_ENTRY_BYTES.saturating_add(string_bytes(units.len()));
let sym = new_symbol(interp, Some(Str::from_rc(units.clone())), true, extra)?;
interp.symbols.registry.insert(units, Value::Symbol(sym.clone()));
Ok(Value::Symbol(sym))
}
/// `Symbol.keyFor(sym)` (section 19.4.2.6).
fn key_for(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
let Value::Symbol(sym) = arg(args, 0) else { return Err(interp.type_error("Symbol.keyFor was given a value that is not a Symbol")) };
Ok(match sym.description() {
Some(d) if sym.registered() => Value::String(d.clone()),
_ => Value::Undefined,
})
}
/// thisSymbolValue (section 19.4.3): a Symbol, or the Symbol of a Symbol object.
fn this_symbol(interp: &mut Interp, this: &Value, name: &str) -> JsResult<Sym> {
let sym = match this {
Value::Symbol(s) => Some(s.clone()),
Value::Object(o) => match interp.heap.object(*o).map(|x| &x.class) {
Some(Class::Symbol(s)) => Some(s.clone()),
_ => None,
},
_ => None,
};
sym.ok_or_else(|| interp.type_error(&format!("Symbol.prototype.{name} was called on a value that is not a Symbol")))
}
/// `Symbol.prototype.toString` (section 19.4.3.3): `Symbol(description)`.
fn to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
let sym = this_symbol(interp, &this, "toString")?;
interp.descriptive_string(&sym)
}
/// `Symbol.prototype.valueOf` (section 19.4.3.4).
fn value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
this_symbol(interp, &this, "valueOf").map(Value::Symbol)
}
/// The getter of `Symbol.prototype.description` (section 19.4.3.2).
fn description(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
let sym = this_symbol(interp, &this, "description")?;
Ok(sym.description().map_or(Value::Undefined, |d| Value::String(d.clone())))
}
/// `Symbol.prototype[@@toPrimitive](hint)` (section 19.4.3.5).
fn symbol_to_primitive(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
this_symbol(interp, &this, "[Symbol.toPrimitive]").map(Value::Symbol)
}
/// `Date.prototype[@@toPrimitive](hint)` (section 20.4.4.45): OrdinaryToPrimitive of any object,
/// `toString` first for the hints `"string"` and `"default"` and `valueOf` first for `"number"`.
/// Any other hint, or a `this` that is not an object, throws a `TypeError`.
fn date_to_primitive(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let Value::Object(o) = this else {
return Err(interp.type_error("Date.prototype[Symbol.toPrimitive] was called on a value that is not an object"));
};
// The longest hint has 7 units, so a longer string is refused before it is flattened.
let name = match arg(args, 0) {
Value::String(s) if s.len() <= 7 => String::from_utf16_lossy(&s.flat()),
_ => String::new(),
};
let hint = match name.as_str() {
"string" | "default" => Hint::String,
"number" => Hint::Number,
_ => return Err(interp.type_error("Date.prototype[Symbol.toPrimitive] was given a hint that is not \"string\", \"number\" or \"default\"")),
};
interp.ordinary_to_primitive(o, &this, hint)
}
/// `Object.getOwnPropertySymbols(o)` (section 19.1.2.10): the object's own Symbol keys in the
/// order they were added.
fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
let o = interp.to_object(&arg(args, 0))?;
interp.rooted(&[Value::Object(o)], |interp| {
let syms = interp.own_symbols(o)?;
let a = new_array(interp, 0)?;
interp.rooted(&[Value::Object(a)], |interp| {
for (i, s) in syms.into_iter().enumerate() {
interp.use_fuel()?;
create_at(interp, a, i as f64, Value::Symbol(s))?;
}
Ok(Value::Object(a))
})
})
}
/// `Function.prototype[@@hasInstance](v)` (section 19.2.3.6): OrdinaryHasInstance.
fn function_has_instance(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
interp.ordinary_has_instance(&arg(args, 0), &this).map(Value::Bool)
}
+4
View File
@@ -684,6 +684,10 @@ fn json_stringify_unwraps_number_string_and_boolean_objects() {
assert_eq!(string("Object.prototype.valueOf = function () { return 9; }; JSON.stringify(Object(3))"), "3");
assert_eq!(string("Object.getPrototypeOf(Object(1)).valueOf = function () { return 4; }; JSON.stringify(Object(3))"), "4");
assert_eq!(string("Object.getPrototypeOf(Object('')).toString = function () { return 'q'; }; JSON.stringify(Object('abc'))"), "\"q\"");
// Once the own prototype's method is deleted, the lookup goes on to Object.prototype.
let over = "Object.prototype.toString = function () { return '7'; };";
assert_eq!(string(&format!("{over} delete String.prototype.toString; JSON.stringify(Object('abc'))")), "\"7\"");
assert_eq!(string(&format!("{over} delete Number.prototype.valueOf; delete Number.prototype.toString; JSON.stringify(Object(3))")), "7");
}
#[test]
+89 -4
View File
@@ -136,6 +136,15 @@ pub(crate) enum Op {
/// `object function` → `object`.
InitGetter(u32),
InitSetter(u32),
/// `object value` → `object`: `__proto__: value` sets the object's prototype to the value
/// when it is an object or `null` (ECMA-262 2015 section B.3.1).
InitProto,
/// `function` → `function`: gives the new function the `name` `names[i]` (ECMA-262 2015
/// section 9.2.11).
SetFunctionName(u32),
/// `name function` → `name function`: gives the new function the computed `name` on the
/// stack, after the prefix.
SetFunctionNameKey(NamePrefix),
/// Pushes a new function made from `functions[i]` and the current environment.
Closure(u32),
/// Pushes a new regular expression object for `regexps[i]`.
@@ -214,6 +223,29 @@ pub(crate) enum Op {
ToStr,
/// Pushes the template object of `templates[i]`, the same object for each evaluation.
TemplateObject(u32),
/// `value` → its Iterator Record (GetIterator, ECMA-262 11th edition section 7.4.1).
GetIterator,
/// `record` → `record value`, or jumps with `record` when the iterator is done.
IterStep(u32),
/// `record x₁…xₙ` → `record x₁…xₙ value`: the next value, `undefined` once it is done.
IterValue(u32),
/// `record` → `record`: steps the iterator without reading the result's `value`, for a hole
/// in an array pattern.
IterSkip,
/// `record x₁…xₙ` → `record x₁…xₙ array`: the values left, in an array.
IterRest(u32),
/// `record` → nothing: closes the iterator unless it is done (IteratorClose).
IterClose,
/// `record exception` → throws the exception after closing the iterator unless it is done.
IterCloseThrow,
/// `value` → `value`: a `TypeError` when it is `undefined` or `null`.
RequireObjectCoercible,
/// `object key x₁…xₙ` → `object key x₁…xₙ object[key]`: an object pattern's property.
PatternGet(u32),
/// `object key value` → `object`: a property with a computed name.
InitIndex,
/// `object key function` → `object`: a getter (`true`) or a setter with a computed name.
InitAccessorIndex(bool),
}
/// The names a block declares, entered with [`Op::PushBlock`].
@@ -305,9 +337,53 @@ pub(crate) struct Code {
pub(crate) arrow: bool,
/// The code reads `this` or calls `eval`, itself or in an arrow function inside it.
pub(crate) uses_this: bool,
/// The function has default or rest parameters: its parameters start uninitialized, its
/// code initializes them and then enters its body with [`Op::BodyEnv`].
/// The function has default, rest or destructured parameters: its parameters start
/// uninitialized, its code initializes them and then enters its body with [`Op::BodyEnv`].
pub(crate) param_init: bool,
/// The names the destructured parameters bind, which start uninitialized beside the
/// parameters. A destructured parameter's own entry in `params` is a name no script can
/// write.
pub(crate) pattern_names: Vec<Key>,
/// The code was read with [`crate::Options::es2015`]: its function's `length` can be
/// redefined, as ECMA-262 2015 section 19.2.4.1 has it.
pub(crate) es2015: bool,
/// The `name` its function objects get when they are made (ECMA-262 2015 sections 14.1.19
/// and 14.1.20): a declaration's or a named function expression's name, with
/// [`crate::Options::es2015`].
pub(crate) own_name: Option<Key>,
/// The code is a method's, a getter's or a setter's, read with [`crate::Options::es2015`]:
/// its functions have no `prototype` and cannot be constructed (section 14.3.8).
pub(crate) method: bool,
}
/// What [`Op::SetFunctionNameKey`] puts before a computed name: `get ` and `set ` for accessors.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum NamePrefix {
None,
Get,
Set,
}
impl NamePrefix {
/// The prefix's code units, with the space that follows it.
pub(crate) fn units(self) -> &'static [u16] {
const GET: &[u16] = &[0x67, 0x65, 0x74, 0x20];
const SET: &[u16] = &[0x73, 0x65, 0x74, 0x20];
match self {
NamePrefix::None => &[],
NamePrefix::Get => GET,
NamePrefix::Set => SET,
}
}
/// The prefix with the space that follows it, as text.
pub(crate) fn text(self) -> &'static str {
match self {
NamePrefix::None => "",
NamePrefix::Get => "get ",
NamePrefix::Set => "set ",
}
}
}
impl Code {
@@ -361,7 +437,9 @@ fn effect(op: Op, finally_tables: &[Vec<u32>]) -> Result<Effect, String> {
Op::Neg | Op::Plus | Op::BitNot | Op::Not | Op::Typeof | Op::ToNumber | Op::ArrayHole | Op::ForInStart | Op::CheckObject => e(1, 1),
Op::GetMemberThis(_) => e(1, 2),
Op::SetMember(_) | Op::GetIndex | Op::DeleteIndex | Op::IncIndex { .. } | Op::Binary(_) => e(2, 1),
Op::ArrayPush | Op::InitProp(_) | Op::InitGetter(_) | Op::InitSetter(_) => e(2, 1),
Op::ArrayPush | Op::InitProp(_) | Op::InitGetter(_) | Op::InitSetter(_) | Op::InitProto => e(2, 1),
Op::SetFunctionName(_) => e(1, 1),
Op::SetFunctionNameKey(_) => e(2, 2),
Op::GetIndexThis => e(2, 2),
Op::SetIndex => e(3, 1),
Op::Call(n) | Op::CallEval(n) => e(n.checked_add(2).ok_or("operand too large")?, 1),
@@ -391,7 +469,13 @@ fn effect(op: Op, finally_tables: &[Vec<u32>]) -> Result<Effect, String> {
Op::LoadParam(_) | Op::TemplateObject(_) => e(0, 1),
Op::ArraySpread | Op::NewSpread => e(2, 1),
Op::CallSpread(_) => e(3, 1),
Op::ToStr => e(1, 1),
Op::ToStr | Op::GetIterator | Op::IterSkip | Op::RequireObjectCoercible => e(1, 1),
Op::IterStep(t) => Effect { pops: 1, next: Some(2), jumps: vec![(t, 1)] },
Op::IterValue(n) | Op::IterRest(n) => e(n.checked_add(1).ok_or("operand too large")?, n.checked_add(2).ok_or("operand too large")?),
Op::PatternGet(n) => e(n.checked_add(2).ok_or("operand too large")?, n.checked_add(3).ok_or("operand too large")?),
Op::IterClose => e(1, 0),
Op::IterCloseThrow => end(2),
Op::InitIndex | Op::InitAccessorIndex(_) => e(3, 1),
})
}
@@ -418,6 +502,7 @@ fn check_indices(op: Op, code: &Code) -> Result<(), String> {
| Op::InitProp(i)
| Op::InitGetter(i)
| Op::InitSetter(i)
| Op::SetFunctionName(i)
| Op::PushCatch(i)
| Op::InitVar(i)
| Op::LoadParam(i)
+1 -1
View File
@@ -123,7 +123,7 @@ pub fn hex_value(c: u32) -> Option<u32> {
}
}
/// The value of the digit values `digits` in `radix` (8 or 16), rounded once to the nearest number
/// The value of the digit values `digits` in `radix` (2, 8 or 16), rounded once to the nearest number
/// with ties to even (sections 7.8.3 and 9.3.1), or `None` when there are no digits. Digits are
/// kept exactly in a `u128` while they fit; past that, each later digit counts only for its
/// position and for whether any of the dropped bits is set.
+304 -72
View File
@@ -13,17 +13,20 @@
//! chains and labels are compiled with loops; every other kind of nesting is counted, and code
//! nested deeper than [`MAX_DEPTH`] gives a `SyntaxError` instead of exhausting the stack.
mod pattern;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use crate::ast::{
AssignOp, Ast, BinaryOp, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LexKind, LogicalOp, PropertyValue, Stmt, StmtId,
TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
AssignOp, Ast, BinaryOp, Binding, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LexKind, LogicalOp, Property, PropertyKey,
PropertyValue, Stmt, StmtId, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
};
use crate::bytecode::{BlockScope, Code, CodeKind, Handler, Op, Source, Template, fallthrough_effect, verify};
use crate::bytecode::{BlockScope, Code, CodeKind, Handler, NamePrefix, Op, Source, Template, fallthrough_effect, verify};
use crate::error::{SyntaxError, TOO_DEEP};
use crate::heap::Key;
use crate::value::Str;
use pattern::Mode;
/// How deeply the compiler may recurse: past the parser's default nesting limit, and shallow
/// enough for a 1 MiB stack.
@@ -61,6 +64,10 @@ enum Ctx {
Jump { labels: Vec<String>, is_loop: bool, plain_break: bool, brk: Label, cont: Option<Label>, depth: u32, env_depth: u32 },
/// The protected part (and catch clause) of a `try` with a `finally` block.
Finally { try_depth: u32, env_depth: u32, entry: Label, exits: Vec<Exit> },
/// The body of a `for-of` loop, whose Iterator Record is the top value at `depth`: a jump
/// out of the loop goes to the label `exits` holds for it, after the loop's protected range,
/// where the iterator is closed and the jump goes on.
Iterator { depth: u32, env_depth: u32, exits: Vec<(Exit, Label)> },
}
struct FnCompiler<'a> {
@@ -271,7 +278,7 @@ impl<'a> FnCompiler<'a> {
scopes.len() - 1
};
match stmt {
Stmt::Var(decls) => decls.iter().for_each(|d| add_var(&mut out, key_of(&d.name.name))),
Stmt::Var(decls) => decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).for_each(|n| add_var(&mut out, key_of(&n.name))),
Stmt::Lexical(..) => {}
Stmt::FunctionDecl(fid) => {
let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else {
@@ -306,21 +313,25 @@ impl<'a> FnCompiler<'a> {
Stmt::For { init, body, .. } => {
let s = match init {
Some(ForInit::Var(decls)) => {
decls.iter().for_each(|d| add_var(&mut out, key_of(&d.name.name)));
decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).for_each(|n| add_var(&mut out, key_of(&n.name)));
scope
}
Some(ForInit::Lexical(_, decls)) => enter(decls.iter().map(|d| key_of(&d.name.name)).collect(), HashSet::new()),
Some(ForInit::Lexical(_, decls)) => {
enter(decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).map(|n| key_of(&n.name)).collect(), HashSet::new())
}
_ => scope,
};
work.push((*body, nested || inner, s));
}
Stmt::ForIn { target, body, .. } => {
Stmt::ForIn { target, body, .. } | Stmt::ForOf { target, body, .. } => {
let s = match target {
ForInTarget::Var(d) => {
add_var(&mut out, key_of(&d.name.name));
self.ast.bound_names(&d.target).iter().for_each(|n| add_var(&mut out, key_of(&n.name)));
scope
}
ForInTarget::Lexical(_, name) => enter(HashSet::from([key_of(&name.name)]), HashSet::new()),
ForInTarget::Lexical(_, binding) => {
enter(self.ast.bound_names(binding).iter().map(|n| key_of(&n.name)).collect(), HashSet::new())
}
ForInTarget::Expr(_) => scope,
};
work.push((*body, nested || inner, s));
@@ -339,7 +350,14 @@ impl<'a> FnCompiler<'a> {
work.extend(f.iter().rev().map(|&st| (st, nested || inner, s)));
}
if let Some(h) = handler {
let s = enter(self.lexical_names(&h.body), self.block_function_names(&h.body));
// A `var` cannot redeclare a destructured catch parameter's names
// (ECMA-262 11th edition section B.3.5), so a block function of that name
// in the body is not also made a `var` (section B.3.3).
let mut names = self.lexical_names(&h.body);
if matches!(h.param, Binding::Pattern(_)) {
names.extend(self.bound_keys(&h.param));
}
let s = enter(names, self.block_function_names(&h.body));
work.extend(h.body.iter().rev().map(|&st| (st, nested || inner, s)));
}
let s = enter(self.lexical_names(block), self.block_function_names(block));
@@ -378,7 +396,7 @@ impl<'a> FnCompiler<'a> {
fn lexical_names(&self, list: &[StmtId]) -> HashSet<Key> {
list.iter()
.filter_map(|&s| match self.ast.stmt(s) {
Some(Stmt::Lexical(_, decls)) => Some(decls.iter().map(|d| key_of(&d.name.name))),
Some(Stmt::Lexical(_, decls)) => Some(decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).map(|n| key_of(&n.name))),
_ => None,
})
.flatten()
@@ -416,7 +434,7 @@ impl<'a> FnCompiler<'a> {
let mut scope = BlockScope::default();
for &s in list {
if let Some(Stmt::Lexical(kind, decls)) = self.ast.stmt(s) {
scope.lets.extend(decls.iter().map(|d| (key_of(&d.name.name), *kind == LexKind::Const)));
scope.lets.extend(decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).map(|n| (key_of(&n.name), *kind == LexKind::Const)));
continue;
}
let Some((decl, fid)) = self.declared_function(s).filter(|(decl, _)| functions && !self.top_funcs.contains(decl)) else { continue };
@@ -454,13 +472,13 @@ impl<'a> FnCompiler<'a> {
/// `let` or `const` declarations: each binding initialized with its value or `undefined`.
fn lexical_decls(&mut self, decls: &[VarDecl]) -> CResult<()> {
for d in decls {
match d.init {
Some(init) => self.expr(init)?,
None => self.emit(Op::Undefined),
match (d.init, &d.target) {
(Some(init), Binding::Name(name)) => self.named_expr(init, &name.name)?,
(Some(init), Binding::Pattern(_)) => self.expr(init)?,
(None, Binding::Name(_)) => self.emit(Op::Undefined),
(None, Binding::Pattern(_)) => return internal("a destructuring declaration without an initializer"),
}
self.at(d.name.span.start);
let n = self.var_name(&d.name.name);
self.emit(Op::InitVar(n));
self.bind_to(&d.target, Mode::Lexical)?;
}
Ok(())
}
@@ -510,7 +528,7 @@ impl<'a> FnCompiler<'a> {
}
Stmt::Block(list) => self.block(list),
Stmt::If { .. } => self.if_chain(id),
Stmt::DoWhile { .. } | Stmt::While { .. } | Stmt::For { .. } | Stmt::ForIn { .. } => self.loop_stmt(id, Vec::new()),
Stmt::DoWhile { .. } | Stmt::While { .. } | Stmt::For { .. } | Stmt::ForIn { .. } | Stmt::ForOf { .. } => self.loop_stmt(id, Vec::new()),
Stmt::Continue(label) => self.jump_stmt(label.as_ref().map(|l| l.name.as_str()), true),
Stmt::Break(label) => self.jump_stmt(label.as_ref().map(|l| l.name.as_str()), false),
Stmt::Return(value) => {
@@ -521,6 +539,7 @@ impl<'a> FnCompiler<'a> {
self.emit_exit(Exit::Return)
}
Stmt::With { object, body } => {
self.statement_completion_start();
self.expr(*object)?;
self.emit(Op::PushWith);
self.env_depth += 1;
@@ -537,7 +556,10 @@ impl<'a> FnCompiler<'a> {
self.emit(Op::Throw);
Ok(())
}
Stmt::Try { block, handler, finalizer } => self.try_stmt(block, handler.as_ref(), finalizer.as_deref()),
Stmt::Try { block, handler, finalizer } => {
self.statement_completion_start();
self.try_stmt(block, handler.as_ref(), finalizer.as_deref())
}
Stmt::DefaultXmlNamespace(e) => {
self.expr(*e)?;
self.emit(Op::SetDefaultNamespace);
@@ -572,11 +594,11 @@ impl<'a> FnCompiler<'a> {
fn var_decls(&mut self, decls: &[VarDecl]) -> CResult<()> {
for d in decls {
if let Some(init) = d.init {
self.expr(init)?;
self.at(d.name.span.start);
let n = self.var_name(&d.name.name);
self.emit(Op::SetVar(n));
self.emit(Op::Pop);
match &d.target {
Binding::Name(name) => self.named_expr(init, &name.name)?,
Binding::Pattern(_) => self.expr(init)?,
}
self.bind_to(&d.target, Mode::Var)?;
}
}
Ok(())
@@ -586,6 +608,7 @@ impl<'a> FnCompiler<'a> {
let saved = self.depth;
let end = self.new_label();
let mut cur = id;
self.statement_completion_start();
while let Some(Stmt::If { test, consequent, alternate }) = self.ast.stmt(cur) {
self.at(self.ast.stmt_span(cur).start);
self.expr(*test)?;
@@ -627,7 +650,9 @@ impl<'a> FnCompiler<'a> {
cur = *body;
}
match self.ast.stmt(cur) {
Some(Stmt::DoWhile { .. } | Stmt::While { .. } | Stmt::For { .. } | Stmt::ForIn { .. }) => self.loop_stmt(cur, labels),
Some(Stmt::DoWhile { .. } | Stmt::While { .. } | Stmt::For { .. } | Stmt::ForIn { .. } | Stmt::ForOf { .. }) => {
self.loop_stmt(cur, labels)
}
Some(Stmt::Switch { .. }) => self.switch_stmt(cur, labels),
_ => {
let brk = self.new_label();
@@ -652,11 +677,30 @@ impl<'a> FnCompiler<'a> {
r
}
/// With [`crate::Options::es2015`], in script and eval code, sets the completion value to
/// `undefined` once before a loop's first test or step, so a loop whose body never completes
/// gives `undefined` (ECMA-262 2015 sections 13.7.2.6, 13.7.3.6, 13.7.4.8 and 13.7.5.13).
fn loop_completion_start(&mut self) {
if self.es2015 && self.kind != CodeKind::Function {
self.emit(Op::Undefined);
self.emit(Op::SetCompletion);
}
}
/// With [`crate::Options::es2015`], in script and eval code, sets the completion value to
/// `undefined` before an `if`, `switch`, `with` or `try` statement, which completes with
/// `undefined` when its body gives no value (ECMA-262 2015 sections 13.6.7, 13.11.7, 13.12.11
/// and 13.15.8). An empty statement keeps the earlier value.
fn statement_completion_start(&mut self) {
self.loop_completion_start();
}
fn loop_stmt(&mut self, id: StmtId, labels: Vec<String>) -> CResult<()> {
let brk = self.new_label();
let cont = self.new_label();
match self.ast.stmt(id) {
Some(Stmt::While { test, body }) => {
self.loop_completion_start();
self.bind(cont);
self.expr(*test)?;
self.jump(Op::JumpIfFalse, brk);
@@ -665,6 +709,7 @@ impl<'a> FnCompiler<'a> {
}
Some(Stmt::DoWhile { body, test }) => {
let top = self.new_label();
self.loop_completion_start();
self.bind(top);
self.loop_body(*body, labels, brk, cont)?;
self.bind(cont);
@@ -684,6 +729,7 @@ impl<'a> FnCompiler<'a> {
}
None => {}
}
self.loop_completion_start();
let head = self.new_label();
self.bind(head);
if let Some(t) = test {
@@ -699,6 +745,7 @@ impl<'a> FnCompiler<'a> {
self.jump(Op::Jump, head);
}
Some(Stmt::ForIn { target, object, body, each }) => return self.for_in(target, *object, *body, labels, *each),
Some(Stmt::ForOf { target, iterable, body }) => return self.for_of(target, *iterable, *body, labels),
_ => return internal("not a loop"),
}
self.bind(brk);
@@ -720,7 +767,8 @@ impl<'a> FnCompiler<'a> {
brk: Label,
cont: Label,
) -> CResult<()> {
let scope = BlockScope { lets: decls.iter().map(|d| (key_of(&d.name.name), kind == LexKind::Const)).collect(), funcs: Vec::new() };
let lets = decls.iter().flat_map(|d| self.bound_keys(&d.target)).map(|k| (k, kind == LexKind::Const)).collect();
let scope = BlockScope { lets, funcs: Vec::new() };
let scope = self.push_scope(scope);
self.emit(Op::PushBlock(scope));
self.env_depth += 1;
@@ -729,6 +777,7 @@ impl<'a> FnCompiler<'a> {
if per_iteration {
self.emit(Op::CopyEnv);
}
self.loop_completion_start();
let head = self.new_label();
self.bind(head);
if let Some(t) = test {
@@ -753,21 +802,15 @@ impl<'a> FnCompiler<'a> {
/// `for (let x in o)`, `for (const x in o)` and `for each` with them: the object read where
/// `x` is not yet initialized, then a new binding of `x` for each name.
fn for_in_lexical(
&mut self,
kind: LexKind,
name: &crate::ast::Name,
object: ExprId,
body: StmtId,
labels: Vec<String>,
each: bool,
) -> CResult<()> {
let scope = self.push_scope(BlockScope { lets: vec![(key_of(&name.name), kind == LexKind::Const)], funcs: Vec::new() });
fn for_in_lexical(&mut self, kind: LexKind, binding: &Binding, object: ExprId, body: StmtId, labels: Vec<String>, each: bool) -> CResult<()> {
let lets = self.bound_keys(binding).into_iter().map(|k| (k, kind == LexKind::Const)).collect();
let scope = self.push_scope(BlockScope { lets, funcs: Vec::new() });
self.emit(Op::PushBlock(scope));
self.env_depth += 1;
self.expr(object)?;
self.emit(Op::PopEnv);
self.env_depth -= 1;
self.loop_completion_start();
self.emit(Op::ForInStart);
let iter_depth = self.depth;
let head = self.new_label();
@@ -777,15 +820,13 @@ impl<'a> FnCompiler<'a> {
let outer_env = self.env_depth;
self.emit(Op::PushBlock(scope));
self.env_depth += 1;
self.at(name.span.start);
let n = self.var_name(&name.name);
if each {
// The value initializes the binding; the name under it goes next.
self.emit(Op::ForEachValue(0));
self.emit(Op::InitVar(n));
self.bind_to(binding, Mode::Lexical)?;
self.emit(Op::Pop);
} else {
self.emit(Op::InitVar(n));
self.bind_to(binding, Mode::Lexical)?;
}
self.contexts.push(Ctx::Jump { labels, is_loop: true, plain_break: true, brk, cont: Some(head), depth: self.depth, env_depth: outer_env });
let r = self.stmt(body);
@@ -801,13 +842,14 @@ impl<'a> FnCompiler<'a> {
}
fn for_in(&mut self, target: &ForInTarget, object: ExprId, body: StmtId, labels: Vec<String>, each: bool) -> CResult<()> {
if let ForInTarget::Lexical(kind, name) = target {
return self.for_in_lexical(*kind, name, object, body, labels, each);
if let ForInTarget::Lexical(kind, binding) = target {
return self.for_in_lexical(*kind, binding, object, body, labels, each);
}
if let ForInTarget::Var(d) = target {
self.var_decls(std::slice::from_ref(d))?;
}
self.expr(object)?;
self.loop_completion_start();
self.emit(Op::ForInStart);
let iter_depth = self.depth;
let head = self.new_label();
@@ -816,11 +858,19 @@ impl<'a> FnCompiler<'a> {
self.jump(Op::ForInNext, brk);
match target {
ForInTarget::Var(d) => {
let n = self.var_name(&d.name.name);
if each {
self.emit(Op::ForEachValue(0));
}
self.emit(Op::SetVar(n));
// The target takes a copy; the name or value stays for the pops below.
self.emit(Op::Dup);
self.bind_to(&d.target, Mode::Var)?;
}
ForInTarget::Expr(e) if self.is_pattern(*e) => {
if each {
self.emit(Op::ForEachValue(0));
}
self.emit(Op::Dup);
self.destructure(*e, Mode::Assign)?;
}
ForInTarget::Expr(e) if each => self.store_value_to(*e)?,
ForInTarget::Expr(e) => self.store_key_to(*e)?,
@@ -924,6 +974,7 @@ impl<'a> FnCompiler<'a> {
fn switch_stmt(&mut self, id: StmtId, labels: Vec<String>) -> CResult<()> {
let Some(Stmt::Switch { discriminant, cases }) = self.ast.stmt(id) else { return internal("not a switch") };
self.statement_completion_start();
self.expr(*discriminant)?;
let all: Vec<StmtId> = cases.iter().flat_map(|c| c.body.iter().copied()).collect();
let scope = self.list_scope(&all, true)?;
@@ -974,7 +1025,7 @@ impl<'a> FnCompiler<'a> {
};
hit.then_some(i)
}
Ctx::Finally { .. } => None,
Ctx::Finally { .. } | Ctx::Iterator { .. } => None,
});
match target {
Some(i) => self.emit_exit(if is_continue { Exit::Continue(i) } else { Exit::Break(i) }),
@@ -1013,6 +1064,23 @@ impl<'a> FnCompiler<'a> {
self.route_through_finally(i, exit, try_depth, env_depth, entry)?;
break;
}
Some(&Ctx::Iterator { depth, env_depth, .. }) => {
// The loop is left: the jump goes past the loop's exception handler, where its
// iterator is closed, a `return` keeping its value (see `for_of`).
if exit == Exit::Return {
let Some(under) = self.depth.checked_sub(1 + depth) else { return internal("stack below a for-of loop") };
if under > 0 {
self.emit(Op::PopUnder(under));
}
self.pop_envs(env_depth)?;
self.emit(Op::Swap);
} else {
self.unwind_to(depth, env_depth)?;
}
let label = self.iterator_exit(i, exit)?;
self.jump(Op::Jump, label);
break;
}
None => return internal("context out of range"),
}
}
@@ -1021,6 +1089,19 @@ impl<'a> FnCompiler<'a> {
Ok(())
}
/// The label where the `for-of` loop of the iterator context `ctx` closes its iterator for
/// `exit` and goes on with it.
fn iterator_exit(&mut self, ctx: usize, exit: Exit) -> CResult<Label> {
let Some(Ctx::Iterator { exits, .. }) = self.contexts.get(ctx) else { return internal("not an iterator context") };
if let Some(&(_, label)) = exits.iter().find(|(e, _)| *e == exit) {
return Ok(label);
}
let label = self.new_label();
let Some(Ctx::Iterator { exits, .. }) = self.contexts.get_mut(ctx) else { return internal("not an iterator context") };
exits.push((exit, label));
Ok(label)
}
fn route_through_finally(&mut self, ctx: usize, exit: Exit, try_depth: u32, env_depth: u32, entry: Label) -> CResult<()> {
let Some(Ctx::Finally { exits, .. }) = self.contexts.get_mut(ctx) else { return internal("not a finally context") };
let k = match exits.iter().position(|e| *e == exit) {
@@ -1083,13 +1164,36 @@ impl<'a> FnCompiler<'a> {
self.handlers.push((start, end, catch, try_depth, env_depth));
self.bind(catch);
self.depth = try_depth + 1;
self.at(h.param.span.start);
let n = self.var_name(&h.param.name);
self.emit(Op::PushCatch(n));
self.env_depth += 1;
self.block(&h.body)?;
self.emit(Op::PopEnv);
self.env_depth -= 1;
// A caught exception drops the value the try block gave (ECMA-262 2015 section 13.15.8).
self.statement_completion_start();
match &h.param {
Binding::Name(name) => {
self.at(name.span.start);
let n = self.var_name(&name.name);
self.emit(Op::PushCatch(n));
self.env_depth += 1;
self.block(&h.body)?;
self.emit(Op::PopEnv);
self.env_depth -= 1;
}
Binding::Pattern(p) => {
// The exception is bound to a name no script can write, then destructured
// into the pattern's names (ECMA-262 11th edition section 13.15.7).
self.at(self.ast.expr_span(*p).start);
let n = self.name_key(key_of("\u{0}catch"));
self.emit(Op::PushCatch(n));
self.emit(Op::GetVar(n));
let lets = self.bound_keys(&h.param).into_iter().map(|k| (k, false)).collect();
let scope = self.push_scope(BlockScope { lets, funcs: Vec::new() });
self.emit(Op::PushBlock(scope));
self.env_depth += 2;
self.destructure(*p, Mode::Lexical)?;
self.block(&h.body)?;
self.emit(Op::PopEnv);
self.emit(Op::PopEnv);
self.env_depth -= 2;
}
}
self.bind(after);
}
let Some(fin) = finalizer else { return Ok(()) };
@@ -1388,30 +1492,112 @@ impl<'a> FnCompiler<'a> {
len_u32(self.templates.len() - 1)
}
fn object_literal(&mut self, props: &[crate::ast::Property]) -> CResult<()> {
fn object_literal(&mut self, props: &[Property]) -> CResult<()> {
self.emit(Op::NewObject);
for p in props {
let n = self.name_key(p.key.to_utf16().into());
if let PropertyKey::Computed(k) = p.key {
self.computed_property(k, &p.value)?;
continue;
}
if self.es2015 && p.is_proto_setter(self.ast) {
if let PropertyValue::Init(e) = &p.value {
self.expr(*e)?;
self.emit(Op::InitProto);
}
continue;
}
let units = p.key.to_utf16();
let n = self.name_key(units.clone().into());
match &p.value {
PropertyValue::Init(e) => {
self.expr(*e)?;
if self.es2015 && self.is_anonymous_function(*e) {
self.emit(Op::SetFunctionName(n));
}
self.emit(Op::InitProp(n));
}
PropertyValue::Get(f) => {
let i = self.function(*f)?;
self.emit(Op::Closure(i));
if self.es2015 {
let named = self.name_key([NamePrefix::Get.units(), &units].concat().into());
self.emit(Op::SetFunctionName(named));
}
self.emit(Op::InitGetter(n));
}
PropertyValue::Set(f) => {
let i = self.function(*f)?;
self.emit(Op::Closure(i));
if self.es2015 {
let named = self.name_key([NamePrefix::Set.units(), &units].concat().into());
self.emit(Op::SetFunctionName(named));
}
self.emit(Op::InitSetter(n));
}
PropertyValue::Method(f) => {
let i = self.function(*f)?;
self.emit(Op::Closure(i));
self.emit(Op::SetFunctionName(n));
self.emit(Op::InitProp(n));
}
}
}
Ok(())
}
/// `object` → `object`, with a property whose name is the value of `key` (ECMA-262 11th
/// edition section 12.2.6.8). A function defined there is named after the key (ECMA-262 2015
/// sections 12.2.6.9 and 14.3.8).
fn computed_property(&mut self, key: ExprId, value: &PropertyValue) -> CResult<()> {
self.expr(key)?;
self.emit(Op::ToKey);
match value {
PropertyValue::Init(e) => {
self.expr(*e)?;
if self.is_anonymous_function(*e) {
self.emit(Op::SetFunctionNameKey(NamePrefix::None));
}
self.emit(Op::InitIndex);
}
PropertyValue::Get(f) | PropertyValue::Set(f) => {
let getter = matches!(value, PropertyValue::Get(_));
let i = self.function(*f)?;
self.emit(Op::Closure(i));
self.emit(Op::SetFunctionNameKey(if getter { NamePrefix::Get } else { NamePrefix::Set }));
self.emit(Op::InitAccessorIndex(getter));
}
PropertyValue::Method(f) => {
let i = self.function(*f)?;
self.emit(Op::Closure(i));
self.emit(Op::SetFunctionNameKey(NamePrefix::None));
self.emit(Op::InitIndex);
}
}
Ok(())
}
/// The expression is an anonymous function definition (ECMA-262 2015 section 14.1.9): a
/// function expression without a name or an arrow function, parenthesized or not.
fn is_anonymous_function(&self, e: ExprId) -> bool {
match self.ast.expr(self.ast.unparenthesized(e)) {
Some(Expr::Arrow(_)) => true,
Some(Expr::Function(fid)) => self.ast.function(*fid).is_some_and(|f| f.name.is_none()),
_ => false,
}
}
/// Compiles `e`; with [`crate::Options::es2015`], an anonymous function definition gets the
/// `name` `name`, as a binding, parameter or assignment gives it (ECMA-262 2015 sections
/// 12.14.4, 13.3.1.4, 13.3.2.4 and 14.1.18).
fn named_expr(&mut self, e: ExprId, name: &str) -> CResult<()> {
self.expr(e)?;
if self.es2015 && self.is_anonymous_function(e) {
let n = self.name_key(key_of(name));
self.emit(Op::SetFunctionName(n));
}
Ok(())
}
/// A run of member accesses and calls (`a.b[c](d).e`), compiled from the innermost object out
/// with a loop.
fn chain(&mut self, id: ExprId) -> CResult<()> {
@@ -1746,7 +1932,19 @@ impl<'a> FnCompiler<'a> {
self.at(self.ast.expr_span(node).start);
self.assign_target(op, target)?;
}
self.expr(cur)?;
// `name = function () {}` names the function after an identifier written without
// parentheses (ECMA-262 2015 section 12.14.4).
let named = chain.last().and_then(|&(op, _, node)| match self.ast.expr(node) {
Some(Expr::Assign { target, .. }) if op.is_none() => match self.ast.expr(*target) {
Some(Expr::Ident(name)) => Some(name.clone()),
_ => None,
},
_ => None,
});
match named {
Some(name) => self.named_expr(cur, &name)?,
None => self.expr(cur)?,
}
for &(op, target, node) in chain.iter().rev() {
self.at(self.ast.expr_span(node).start);
if let Some(b) = op {
@@ -1760,6 +1958,9 @@ impl<'a> FnCompiler<'a> {
/// Pushes what an assignment to `target` needs before its value: the object and key, and the
/// current value for a compound assignment.
fn assign_target(&mut self, op: AssignOp, target: ExprId) -> CResult<()> {
if op.is_none() && self.es2015 && self.is_pattern(target) {
return Ok(());
}
match self.ast.expr(target) {
Some(Expr::Ident(name)) => {
let n = self.var_name(name);
@@ -1806,6 +2007,11 @@ impl<'a> FnCompiler<'a> {
}
fn store(&mut self, target: ExprId) -> CResult<()> {
if self.es2015 && self.is_pattern(target) {
// The assignment's value is the value assigned (ECMA-262 11th edition section 12.15.4).
self.emit(Op::Dup);
return self.destructure(target, Mode::Assign);
}
match self.ast.expr(target) {
Some(Expr::Ident(name)) => {
let n = self.var_name(name);
@@ -1868,6 +2074,7 @@ impl<'a> FnCompiler<'a> {
| Op::JumpIfNotNullishKeep(t)
| Op::JumpIfNullish { target: t, .. }
| Op::ForInNext(t)
| Op::IterStep(t)
| Op::XmlFilterNext(t),
) => *t = target,
_ => return internal("patching an instruction that is not a jump"),
@@ -1912,6 +2119,10 @@ impl<'a> FnCompiler<'a> {
arrow: meta.arrow,
uses_this: self.uses_this,
param_init: meta.param_init,
pattern_names: meta.pattern_names,
es2015: self.es2015,
own_name: meta.own_name,
method: meta.method,
};
code.max_stack = verify(&code).map_err(CompileFail::Internal)?;
Ok(Rc::new(code))
@@ -1930,6 +2141,9 @@ struct Meta {
length: u32,
arrow: bool,
param_init: bool,
pattern_names: Vec<Key>,
own_name: Option<Key>,
method: bool,
}
fn len_u32(n: usize) -> u32 {
@@ -1944,37 +2158,52 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>,
c.es2015 = es2015;
c.at(f.span.start);
c.enter()?;
let params: Vec<Key> = f.params.iter().map(|p| key_of(&p.name)).collect();
let rest = f.rest.as_ref().map(|r| key_of(&r.name));
let all_params: Vec<Key> = params.iter().chain(&rest).cloned().collect();
// A destructured parameter has a binding of its own under a name no script can write, which
// holds its argument until the pattern takes it.
let param_key = |c: &FnCompiler, i: usize, p: &Binding| match p {
Binding::Name(n) => key_of(&n.name),
Binding::Pattern(_) => c.hidden_param(i),
};
let params: Vec<Key> = f.params.iter().enumerate().map(|(i, p)| param_key(&c, i, p)).collect();
let rest = f.rest.as_ref().map(|r| param_key(&c, f.params.len(), r));
let pattern_names: Vec<Key> = f.params.iter().chain(&f.rest).filter(|p| matches!(p, Binding::Pattern(_))).flat_map(|p| c.bound_keys(p)).collect();
let all_params: Vec<Key> = f.params.iter().chain(&f.rest).flat_map(|p| c.bound_keys(p)).collect();
let hoisted = c.hoist(&f.body, &all_params)?;
let top_scope = c.list_scope(&f.body, false)?;
let param_init = !f.simple_params();
if param_init {
// Each parameter is initialized in order, from its argument or, when that is
// `undefined`, its default value; then the body's environment is entered.
for (i, p) in f.params.iter().enumerate() {
c.at(p.span.start);
let n = c.var_name(&p.name);
let all = f.params.iter().enumerate().map(|(i, p)| (p, f.defaults.get(i).copied().flatten())).chain(f.rest.iter().map(|r| (r, None)));
for (i, (p, default)) in all.enumerate() {
let k = params.get(i).or(rest.as_ref()).cloned().unwrap_or_default();
let n = c.name_key(k);
c.at(match p {
Binding::Name(name) => name.span.start,
Binding::Pattern(e) => ast.expr_span(*e).start,
});
c.emit(Op::LoadParam(n));
if let Some(Some(default)) = f.defaults.get(i) {
if let Some(default) = default {
let skip = c.new_label();
c.emit(Op::Dup);
c.emit(Op::Undefined);
c.emit(Op::Binary(BinaryOp::StrictEq));
c.jump(Op::JumpIfFalse, skip);
c.emit(Op::Pop);
c.expr(*default)?;
match p {
Binding::Name(name) => c.named_expr(default, &name.name)?,
Binding::Pattern(_) => c.expr(default)?,
}
c.bind(skip);
}
c.at(p.span.start);
c.emit(Op::InitVar(n));
}
if let Some(r) = &f.rest {
c.at(r.span.start);
let n = c.var_name(&r.name);
c.emit(Op::LoadParam(n));
c.emit(Op::InitVar(n));
match p {
Binding::Name(name) => {
c.at(name.span.start);
let n = c.var_name(&name.name);
c.emit(Op::InitVar(n));
}
Binding::Pattern(e) => c.destructure(*e, Mode::Lexical)?,
}
}
c.emit(Op::BodyEnv);
}
@@ -1994,6 +2223,9 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>,
length: len_u32(length),
arrow: f.kind == FunctionKind::Arrow,
param_init,
pattern_names,
own_name: es2015.then(|| key_of(f.name.as_ref().map_or("", |n| n.name.as_str()))),
method: es2015 && matches!(f.kind, FunctionKind::Method | FunctionKind::Getter | FunctionKind::Setter),
};
c.finish(hoisted, meta)
}
+316
View File
@@ -0,0 +1,316 @@
//! Destructuring and `for (… of …)` (ECMA-262 11th edition,
//! <https://262.ecma-international.org/11.0/>, sections 12.15.5, 13.3.3 and 13.7.5).
//!
//! A pattern takes the value on top of the stack. An array pattern steps the value's iterator
//! once for each element and closes it when the pattern ends with the iterator not done, and when
//! anything in the pattern throws (an exception handler around the elements). An object pattern
//! reads each property by name. A target that is not a pattern is written as an assignment
//! (`[a.b] = …`), a `var` or a `let`, `const`, parameter or catch binding, as [`Mode`] says.
use super::{CResult, Ctx, Exit, FnCompiler, internal, key_of, len_u32};
use crate::ast::{Binding, Expr, ExprId, ForInTarget, LexKind, Property, PropertyKey, PropertyValue, StmtId};
use crate::bytecode::{BlockScope, CodeKind, Op};
use crate::heap::Key;
/// How a pattern's targets are written.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Mode {
/// An assignment: each target is evaluated as an assignment's target is.
Assign,
/// `var`: the variable is assigned.
Var,
/// `let`, `const`, a parameter or a catch clause: the binding is initialized.
Lexical,
}
impl FnCompiler<'_> {
/// Whether `id`, without parentheses, is an array or object pattern.
pub(super) fn is_pattern(&self, id: ExprId) -> bool {
matches!(self.ast.expr(self.ast.unparenthesized(id)), Some(Expr::Array(_) | Expr::Object(_)))
}
/// The names a binding binds, as keys.
pub(super) fn bound_keys(&self, binding: &Binding) -> Vec<Key> {
self.ast.bound_names(binding).iter().map(|n| key_of(&n.name)).collect()
}
/// `value` → nothing: writes the value to the targets of the pattern `pattern`.
pub(super) fn destructure(&mut self, pattern: ExprId, mode: Mode) -> CResult<()> {
self.enter()?;
let pattern = self.ast.unparenthesized(pattern);
self.at(self.ast.expr_span(pattern).start);
let r = match self.ast.expr(pattern) {
Some(Expr::Array(elements)) => self.array_pattern(elements, mode),
Some(Expr::Object(properties)) => self.object_pattern(properties, mode),
_ => internal("not a destructuring pattern"),
};
self.leave();
r
}
/// `value` → nothing: writes the value to a name binding or a pattern.
pub(super) fn bind_to(&mut self, binding: &Binding, mode: Mode) -> CResult<()> {
match binding {
Binding::Pattern(p) => self.destructure(*p, mode),
Binding::Name(name) => {
self.at(name.span.start);
let n = self.var_name(&name.name);
if mode == Mode::Lexical {
self.emit(Op::InitVar(n));
} else {
self.emit(Op::SetVar(n));
self.emit(Op::Pop);
}
Ok(())
}
}
}
/// An element's target and its default value.
fn split_default(&self, element: ExprId) -> (ExprId, Option<ExprId>) {
match self.ast.expr(element) {
Some(Expr::Assign { op: None, target, value }) => (*target, Some(*value)),
_ => (element, None),
}
}
/// Pushes what writing to `target` needs before its value, and gives how many values that is:
/// an assignment's object and key; a `var` name's reference, resolved before the value is
/// read (sections 13.3.3.6 and 13.3.3.7); nothing for another binding or a pattern.
fn target_refs(&mut self, target: ExprId, mode: Mode) -> CResult<u32> {
if mode == Mode::Var
&& let Some(Expr::Ident(name)) = self.ast.expr(target)
{
self.at(self.ast.expr_span(target).start);
let n = self.var_name(name);
self.emit(Op::RefVar(n));
return Ok(1);
}
if mode != Mode::Assign || self.is_pattern(target) {
return Ok(0);
}
let before = self.depth;
self.assign_target(None, self.ast.unparenthesized(target))?;
Ok(self.depth.saturating_sub(before))
}
/// `refs… value` → nothing: writes the value to `target`.
fn write_target(&mut self, target: ExprId, mode: Mode) -> CResult<()> {
let target = self.ast.unparenthesized(target);
if self.is_pattern(target) {
return self.destructure(target, mode);
}
self.at(self.ast.expr_span(target).start);
match (mode, self.ast.expr(target)) {
(Mode::Assign, _) => {
self.store(target)?;
self.emit(Op::Pop);
}
(_, Some(Expr::Ident(name))) => {
let n = self.var_name(name);
if mode == Mode::Lexical {
self.emit(Op::InitVar(n));
} else {
self.emit(Op::PutRef(n));
self.emit(Op::Pop);
}
}
_ => return internal("a binding pattern's target is not a name"),
}
Ok(())
}
/// `value` → `value`, or the default value when the value is `undefined`. An anonymous
/// function as the default value of a plain name gets that name (ECMA-262 2015 sections
/// 12.14.5.3, 12.14.5.4, 13.3.3.6 and 13.3.3.7).
fn default_value(&mut self, target: ExprId, default: Option<ExprId>) -> CResult<()> {
let Some(default) = default else { return Ok(()) };
let skip = self.new_label();
self.emit(Op::Dup);
self.emit(Op::Undefined);
self.emit(Op::Binary(crate::ast::BinaryOp::StrictEq));
self.jump(Op::JumpIfFalse, skip);
self.emit(Op::Pop);
match self.ast.expr(target) {
Some(Expr::Ident(name)) => self.named_expr(default, name)?,
_ => self.expr(default)?,
}
self.bind(skip);
Ok(())
}
/// `value` → nothing, for `[a, , b = 1, ...c]` (sections 12.15.5.5 and 13.3.3.6).
fn array_pattern(&mut self, elements: &[Option<ExprId>], mode: Mode) -> CResult<()> {
self.emit(Op::GetIterator);
let record = self.depth;
let start = self.pc();
for element in elements {
let Some(element) = *element else {
self.emit(Op::IterSkip);
continue;
};
if let Some(Expr::Spread(target)) = self.ast.expr(element) {
let under = self.target_refs(*target, mode)?;
self.emit(Op::IterRest(under));
self.write_target(*target, mode)?;
continue;
}
let (target, default) = self.split_default(element);
let under = self.target_refs(target, mode)?;
self.emit(Op::IterValue(under));
self.default_value(target, default)?;
self.write_target(target, mode)?;
}
let end = self.pc();
let close_throw = self.new_label();
let after = self.new_label();
self.emit(Op::IterClose);
self.jump(Op::Jump, after);
self.handlers.push((start, end, close_throw, record, self.env_depth));
self.bind(close_throw);
self.depth = record + 1;
self.emit(Op::IterCloseThrow);
self.bind(after);
self.depth = record.saturating_sub(1);
Ok(())
}
/// `value` → nothing, for `{a, b: c, [d]: e = 1}` (sections 12.15.5.4 and 13.3.3.5).
fn object_pattern(&mut self, properties: &[Property], mode: Mode) -> CResult<()> {
self.emit(Op::RequireObjectCoercible);
for p in properties {
let PropertyValue::Init(value) = p.value else { return internal("a method, getter or setter in a pattern") };
self.at(p.span.start);
match &p.key {
PropertyKey::Computed(e) => {
self.expr(*e)?;
self.emit(Op::ToKey);
}
key => {
let i = self.string(&key.to_utf16());
self.emit(Op::String(i));
}
}
let (target, default) = self.split_default(value);
let under = self.target_refs(target, mode)?;
self.emit(Op::PatternGet(under));
self.default_value(target, default)?;
self.write_target(target, mode)?;
self.emit(Op::Pop);
}
self.emit(Op::Pop);
Ok(())
}
/// `for (target of iterable) body` (sections 13.7.5.12 and 13.7.5.13): the iterable is read
/// where a `let` or `const` head's names are not yet initialized; each step's value goes to
/// the target, in a new environment for a `let` or `const` head; the iterator is closed when
/// the loop is left early, by `break`, `return`, a jump to an outer loop or an exception.
pub(super) fn for_of(&mut self, target: &ForInTarget, iterable: ExprId, body: StmtId, labels: Vec<String>) -> CResult<()> {
let scope = match target {
ForInTarget::Lexical(kind, binding) => {
let constant = *kind == LexKind::Const;
let lets = self.bound_keys(binding).into_iter().map(|k| (k, constant)).collect();
Some(self.push_scope(BlockScope { lets, funcs: Vec::new() }))
}
_ => None,
};
match scope {
Some(s) => {
self.emit(Op::PushBlock(s));
self.env_depth += 1;
self.expr(iterable)?;
self.emit(Op::PopEnv);
self.env_depth -= 1;
}
None => self.expr(iterable)?,
}
// The loop's completion value starts as `undefined` (ForIn/OfBodyEvaluation, step 2).
if self.kind != CodeKind::Function {
self.emit(Op::Undefined);
self.emit(Op::SetCompletion);
}
self.at(self.ast.expr_span(iterable).start);
self.emit(Op::GetIterator);
let record = self.depth;
let outer_env = self.env_depth;
let head = self.new_label();
let brk = self.new_label();
let done = self.new_label();
let close_throw = self.new_label();
let after = self.new_label();
self.contexts.push(Ctx::Iterator { depth: record, env_depth: outer_env, exits: Vec::new() });
self.bind(head);
self.jump(Op::IterStep, done);
let start = self.pc();
if let Some(s) = scope {
self.emit(Op::PushBlock(s));
self.env_depth += 1;
}
let r = self.for_of_target(target);
let r = r.and_then(|()| {
self.push_jump_ctx(labels, true, true, brk, Some(head));
if let Some(Ctx::Jump { env_depth, .. }) = self.contexts.last_mut() {
*env_depth = outer_env;
}
let r = self.stmt(body);
self.contexts.pop();
r
});
let exits = match self.contexts.pop() {
Some(Ctx::Iterator { exits, .. }) => exits,
_ => return internal("for-of context missing"),
};
r?;
if scope.is_some() {
self.emit(Op::PopEnv);
self.env_depth -= 1;
}
let end = self.pc();
self.jump(Op::Jump, head);
self.handlers.push((start, end, close_throw, record, outer_env));
self.bind(close_throw);
self.depth = record + 1;
self.emit(Op::IterCloseThrow);
self.bind(brk);
self.depth = record;
self.emit(Op::IterClose);
self.jump(Op::Jump, after);
// `return` and jumps to outer statements close the iterator here, outside the range the
// loop's handler covers, so an exception from `return` goes to the handlers around the
// loop; the jump then goes on through them.
for (exit, label) in exits {
self.bind(label);
self.depth = if exit == Exit::Return { record + 1 } else { record };
self.env_depth = outer_env;
self.emit(Op::IterClose);
self.emit_exit(exit)?;
}
self.depth = record;
self.env_depth = outer_env;
self.bind(done);
self.depth = record;
self.emit(Op::Pop);
self.bind(after);
Ok(())
}
/// `value` → nothing: a `for-of` loop's step value written to its target.
fn for_of_target(&mut self, target: &ForInTarget) -> CResult<()> {
match target {
ForInTarget::Var(d) => self.bind_to(&d.target, Mode::Var),
ForInTarget::Lexical(_, binding) => self.bind_to(binding, Mode::Lexical),
ForInTarget::Expr(e) if self.is_pattern(*e) => self.destructure(*e, Mode::Assign),
ForInTarget::Expr(e) => {
self.store_key_to(*e)?;
self.emit(Op::Pop);
Ok(())
}
}
}
/// The key of a destructured parameter's own binding, which no script can name.
pub(super) fn hidden_param(&self, i: usize) -> Key {
key_of(&format!("\u{0}p{}", len_u32(i)))
}
}
+594
View File
@@ -0,0 +1,594 @@
//! Object literals with computed names, shorthand properties and methods, and the `name` and
//! `length` of functions, with [`Options::es2015`].
use proptest::prelude::*;
use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind};
fn es_options() -> Options {
Options { es2015: true, ..Options::default() }
}
fn es() -> Realm {
Realm::with_options(es_options(), Limits::default())
}
fn truth(src: &str) {
assert_eq!(es().run(src), Ok(JsValue::Bool(true)), "{src}");
}
/// The script throws an error whose message starts with `name`.
fn throws(src: &str, name: &str) {
match es().run(src) {
Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"),
other => panic!("{src}: {other:?}"),
}
}
/// The script does not parse.
fn syntax(src: &str) {
match es().run(src) {
Err(RunError { kind: RunErrorKind::Syntax, .. }) => {}
other => panic!("{src}: {other:?}"),
}
}
/// Runs `src` with a collection at every heap reservation, and checks that it gives `true`.
fn truth_collecting(src: &str) {
let mut realm = es();
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true));
let r = realm.run(src);
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false));
assert_eq!(r, Ok(JsValue::Bool(true)), "{src}");
assert!(realm.interp().heap.collections > 0, "{src}");
}
/// A script that checks that `f`'s own `name` is `value`, not writable, not enumerable and
/// configurable.
fn name_is(f: &str, value: &str) -> String {
format!(
"(function (f) {{ var d = Object.getOwnPropertyDescriptor(f, 'name'); \
return !!d && d.value === '{value}' && !d.writable && !d.enumerable && d.configurable; }})({f})"
)
}
// ---- object literals ----
#[test]
fn a_shorthand_property_reads_its_binding() {
truth("var a = 1, get = 2, set = 3; var o = { a, get, set }; o.a === 1 && o.get === 2 && o.set === 3");
truth("var a = 1; var d = Object.getOwnPropertyDescriptor({ a }, 'a'); d.writable && d.enumerable && d.configurable");
truth("let x = 'x'; const y = 'y'; var o = { x, y, z: 3 }; Object.keys(o).join() === 'x,y,z'");
throws("({ missing })", "ReferenceError");
throws("({ later }); let later = 1;", "ReferenceError");
}
#[test]
fn methods_are_enumerable_functions_that_cannot_be_constructed() {
truth(
"var o = { k: 1, m(x) { return x + this.k; }, get() { return 'g'; }, set(v) { return v; } }; o.m(1) === 2 && o.get() === 'g' && o.set(4) === 4",
);
truth("var o = { m() {} }; var d = Object.getOwnPropertyDescriptor(o, 'm'); d.enumerable && d.writable && d.configurable");
truth("var o = { m() {} }; !o.m.hasOwnProperty('prototype') && o.m.length === 0");
truth("var o = { m(a, b = 1, ...r) { return arguments.length; } }; o.m.length === 1 && o.m(1, 2, 3) === 3");
throws("var o = { m() {} }; new o.m();", "TypeError");
throws("var o = { get g() { return 1; } }; new (Object.getOwnPropertyDescriptor(o, 'g').get)();", "TypeError");
syntax("({ m(a, a) {} })");
syntax("({ m() { 'use strict'; } , n(a = 1) { 'use strict'; } })");
}
#[test]
fn computed_names_are_evaluated_and_converted_in_order() {
truth("var k = 'a'; var o = { [k + 'b']: 1, [1 + 1]: 2, [k]() { return 3; } }; o.ab === 1 && o[2] === 2 && o.a() === 3");
truth("var v = 0; var o = { get ['x' + 1]() { return v; }, set ['x' + 1](n) { v = n; } }; o.x1 = 5; o.x1 === 5");
truth("var o = { [{ toString() { return 'p'; } }]: 1 }; o.p === 1");
// Each name is converted to a property name before its value is evaluated, entry by entry.
truth(
"var log = []; var key = (n) => ({ toString() { log.push('key' + n); return 'k' + n; } }); \
var val = (n) => { log.push('value' + n); return n; }; \
var o = { [key(1)]: val(1), [key(2)]: val(2) }; \
log.join() === 'key1,value1,key2,value2' && o.k1 === 1 && o.k2 === 2",
);
// A later definition of the same name replaces the earlier one.
truth("var o = { a: 1, ['a']: 2 }; o.a === 2 && Object.keys(o).length === 1");
truth("var o = { get ['a']() { return 1; }, a: 2 }; o.a === 2");
}
#[test]
fn e4x_values_as_computed_names_become_property_names() {
let options = Options { es2015: true, e4x: true, ..Options::default() };
let mut realm = Realm::with_options(options, Limits::default());
let src = "var o; with (<x a='k' b='m'/>) { o = { [@a]: 1, [@b]() { return 2; }, [<y>n</y>]: 3 }; } \
Object.keys(o).join() === 'k,m,n' && o.k === 1 && o.m() === 2 && o.m.name === 'm'";
assert_eq!(realm.run(src), Ok(JsValue::Bool(true)));
}
#[test]
fn a_computed_name_that_throws_stops_the_literal() {
truth(
"var log = []; try { ({ a: log.push('a'), [(() => { throw new Error('k'); })()]: log.push('b'), c: log.push('c') }); } \
catch (e) { log.push(e.message); } log.join() === 'a,k'",
);
throws("({ [{ toString() { throw new TypeError('no name'); } }]: 1 })", "TypeError: no name");
throws("({ [undefinedName]: 1 })", "ReferenceError");
}
#[test]
fn bad_object_literal_forms_are_syntax_errors() {
syntax("({ m() {} } = {});");
syntax("var a; [{ m() {} }] = [];");
syntax("for ({ m() {} } of []) ;");
for src in ["({ if })", "({ this })", "({ 1 })", "({ 'a' })", "({ [a] })", "({ [a }: 1 })", "({ get [a]: 1 })", "({ a() })"] {
syntax(src);
}
syntax("'use strict'; ({ yield })");
syntax("({ \\u0069f })");
syntax("({ get [a](x) {} })");
syntax("({ set [a]() {} })");
}
#[test]
fn proto_sets_the_prototype_once() {
truth("var p = { x: 1 }; var o = { __proto__: p }; Object.getPrototypeOf(o) === p && !o.hasOwnProperty('__proto__') && o.x === 1");
truth("var o = { '__proto__': null }; Object.getPrototypeOf(o) === null");
truth("var o = { __proto__: 1 }; Object.getPrototypeOf(o) === Object.prototype && !o.hasOwnProperty('__proto__')");
truth("var o = { ['__proto__']: 1 }; o.hasOwnProperty('__proto__') && Object.getPrototypeOf(o) === Object.prototype");
truth("var __proto__ = 2; var o = { __proto__ }; o.hasOwnProperty('__proto__') && Object.getPrototypeOf(o) === Object.prototype");
truth("var o = { __proto__() { return 3; } }; o.hasOwnProperty('__proto__') && o.__proto__() === 3");
truth("var __proto__ = 2; var o = { __proto__: null, ['__proto__']: 1, __proto__ }; Object.getPrototypeOf(o) === null");
syntax("({ __proto__: null, __proto__: null })");
syntax("({ __proto__: null, '__proto__': null })");
}
#[test]
fn a_destructuring_pattern_may_name_proto_twice() {
// The value read is an own property named `__proto__`.
truth("var v = { ['__proto__']: 1 }; var a, b; ({ __proto__: a, __proto__: b } = v); a === 1 && b === 1");
truth("var v = { ['__proto__']: 1 }; var a, b; [{ __proto__: a, __proto__: b }] = [v]; a === 1 && b === 1");
truth("var f = ({ __proto__: a, __proto__: b }) => a + b; f({ ['__proto__']: 1 }) === 2");
truth("var r; for ({ __proto__: r, __proto__: r } of [{ ['__proto__']: 3 }]) ; r === 3");
truth("var { __proto__: x, __proto__: y } = { ['__proto__']: 4 }; x === 4 && y === 4");
// The same literal is still an error where it stays a literal, nested or not.
for src in [
"var a, b; ({ __proto__: a, __proto__: b });",
"[{ __proto__: 1, __proto__: 2 }];",
"var b; ({ a: b = { __proto__: 1, __proto__: 2 } } = {});",
"var b; ({ [{ __proto__: 1, __proto__: 2 }]: b } = {});",
"var a; ({ __proto__: a, __proto__: a } = { b: { __proto__: 1, __proto__: 2 } });",
] {
match es().run(src) {
Err(RunError { kind: RunErrorKind::Syntax, message, .. }) => assert!(message.contains("'__proto__' twice"), "{src}: {message}"),
other => panic!("{src}: {other:?}"),
}
}
}
#[test]
fn a_wide_pattern_may_repeat_proto_with_defaults_inside() {
let props = vec!["__proto__: { x = 0 }"; 2_000].join(", ");
truth(&format!("var x; ({{ {props} }} = {{ ['__proto__']: {{}} }}); x === 0"));
// In a literal, the first of the errors in source order is the one reported.
for (src, twice) in [
("({ __proto__: 1, __proto__: 2, a: { b = 1 }, __proto__: 3 });", true),
("({ a: { b = 1 }, __proto__: 1, __proto__: 2 });", false),
("({ __proto__: 1, a: { b = 1 }, __proto__: 2 });", false),
] {
let e = es().run(src).unwrap_err();
assert_eq!((&e.kind, e.message.contains("'__proto__' twice")), (&RunErrorKind::Syntax, twice), "{src}: {e:?}");
}
}
#[test]
fn computed_names_and_methods_stay_reachable_while_they_are_defined() {
truth_collecting(
"var o = { ['a' + 1]: [1], ['b' + 2]() { return 2; }, get ['c' + 3]() { return 3; } }; o.a1[0] === 1 && o.b2() === 2 && o.c3 === 3",
);
truth_collecting("var o = { ['m' + 1]: () => 1 }; o.m1.name === 'm1'");
truth_collecting("function t() {} var b = t.bind(); b.name === 'bound t'");
}
#[test]
fn computed_names_stay_within_the_limits() {
let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() });
let e = realm.run("({ [{ toString() { for (;;) {} } }]: 1 })").unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel), "{e:?}");
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes: 4 << 20, ..Limits::default() });
let e = realm.run("var s = 'x'; for (var i = 0; i < 20; i++) s += s; ({ get [s]() {} })").unwrap_err();
assert!(matches!(e.kind, RunErrorKind::Limit(_)), "{e:?}");
}
/// The smallest heap limit at which a new ECMAScript 2015 realm runs `src` without an error.
fn smallest_heap(src: &str) -> usize {
let runs = |heap_bytes: usize| Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() }).run(src).is_ok();
let (mut lo, mut hi) = (0usize, 64usize << 20);
assert!(runs(hi), "{src}");
while lo + 1 < hi {
let mid = lo + (hi - lo) / 2;
if runs(mid) {
hi = mid;
} else {
lo = mid;
}
}
hi
}
#[test]
fn a_repeated_computed_name_needs_no_more_heap_than_one() {
// The two scripts differ only in `twice`, so they compile to code of the same size.
let script = |twice: u8| {
format!(
"var twice = {twice}; var k = 'x'; for (var i = 0; i < 16; i++) k += k; \
var o = twice ? {{ [k]: 1, [k]: 2 }} : {{ [k]: 1 }}; o[k] === 1 + twice"
)
};
let once = smallest_heap(&script(0));
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes: once, ..Limits::default() });
assert_eq!(realm.run(&script(1)), Ok(JsValue::Bool(true)));
}
#[test]
fn naming_a_function_needs_no_more_heap_than_making_it() {
let script = |named: u8| format!("var named = {named}, f, g; if (named) f = function () {{}}; else g = (0, function () {{}}); true");
let (unnamed, named) = (smallest_heap(&script(0)), smallest_heap(&script(1)));
// A new property takes at least `PROP_BYTES`; giving the made function its name replaces one.
assert!(named < unnamed + crate::heap::PROP_BYTES, "{named} {unnamed}");
}
#[test]
fn bind_stays_within_the_heap_limit() {
for options in [Options::default(), es_options()] {
// The bytes a second run that binds a function adds, measured without a limit.
let ready = || {
let mut realm = Realm::with_options(options.clone(), Limits::default());
assert_eq!(realm.run("function t() {} var b; function go() { b = t.bind(); return true; } true"), Ok(JsValue::Bool(true)));
realm
};
let mut realm = ready();
let before = realm.interp().heap.bytes;
assert_eq!(realm.run("go()"), Ok(JsValue::Bool(true)));
let added = realm.interp().heap.bytes - before;
// With one byte less than that, the run ends at the limit, or a collection makes room,
// and the heap does not pass the limit either way.
let mut realm = ready();
let limit = realm.interp().heap.bytes + added - 1;
realm.set_limits(Limits { heap_bytes: limit, ..Limits::default() });
let r = realm.run("go()");
let used = realm.interp().heap.bytes;
assert!(r.is_ok() || matches!(&r, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)), "{options:?}: {r:?}");
assert!(used <= limit, "{options:?}: {used} of {limit}");
}
}
#[test]
fn computed_keys_stay_within_the_heap_limit() {
let setup = "var ks = [], ss = [], out; for (var i = 0; i < 64; i++) { ks.push('key' + i); ss.push(Symbol()); } true";
let literal = |keys: &str| (0..64).map(|i| format!("[{keys}[{i}]]: {i}")).collect::<Vec<_>>().join(", ");
for go in [
format!("function go() {{ out = {{ {} }}; return true; }} true", literal("ks")),
format!("function go() {{ out = {{ {} }}; return true; }} true", literal("ss")),
] {
// The bytes the object a run of `go` keeps in `out` holds, measured without a limit.
let ready = || {
let mut realm = es();
assert_eq!(realm.run(setup), Ok(JsValue::Bool(true)));
assert_eq!(realm.run(&go), Ok(JsValue::Bool(true)));
realm.collect_garbage();
realm
};
let mut realm = ready();
let before = realm.interp().heap.bytes;
assert_eq!(realm.run("go()"), Ok(JsValue::Bool(true)));
realm.collect_garbage();
let kept = realm.interp().heap.bytes - before;
// With one byte less than that, the run ends at the limit and the heap stays within it.
let mut realm = ready();
let limit = realm.interp().heap.bytes + kept - 1;
realm.set_limits(Limits { heap_bytes: limit, ..Limits::default() });
let e = realm.run("go()").unwrap_err();
let used = realm.interp().heap.bytes;
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{e:?}");
assert!(used <= limit, "{used} of {limit}");
}
}
#[test]
fn a_built_in_made_after_the_names_are_set_checks_the_heap_for_its_name() {
fn nothing(
_: &mut crate::interp::Interp,
_: crate::value::Value,
_: &[crate::value::Value],
_: bool,
) -> crate::interp::JsResult<crate::value::Value> {
Ok(crate::value::Value::Undefined)
}
let mut realm = es();
assert_eq!(realm.run("Math.max.name === 'max'"), Ok(JsValue::Bool(true)));
let limit = realm.collect_garbage();
realm.set_limits(Limits { heap_bytes: limit, ..Limits::default() });
let made = crate::builtins::native(realm.interp(), "later", nothing, 0, crate::heap::NativeKind::Plain, false);
assert!(matches!(made, Err(crate::interp::Abrupt::Limit(LimitKind::Heap))), "{}", made.is_ok());
}
#[test]
fn built_ins_no_script_can_reach_need_no_room_for_names() {
let drop = "[Math, String.prototype, Array.prototype].forEach(function (o) { \
Object.getOwnPropertyNames(o).forEach(function (k) { if (k !== 'constructor') delete o[k]; }); }); true";
// The heap the first ECMAScript 2015 run needs once the dropped built-ins are collected.
let mut realm = Realm::new();
assert_eq!(realm.run(drop), Ok(JsValue::Bool(true)));
realm.collect_garbage();
realm.set_es2015(true);
assert_eq!(realm.run("true"), Ok(JsValue::Bool(true)));
// 4 KiB more covers what compiling the script reserves; the dropped functions' names would
// need several times that.
let limit = realm.interp().heap.bytes + 4096;
let mut realm = Realm::new();
assert_eq!(realm.run(drop), Ok(JsValue::Bool(true)));
realm.set_limits(Limits { heap_bytes: limit, ..Limits::default() });
realm.set_es2015(true);
assert_eq!(realm.run("true"), Ok(JsValue::Bool(true)));
}
#[test]
fn built_in_names_do_not_follow_what_earlier_scripts_did_with_them() {
let mut realm = Realm::new();
let setup = "Object.defineProperty(this, 'max', { get: Math.max, configurable: true }); \
Object.defineProperty(Math.min, 'name', { value: 'mine', configurable: true }); true";
assert_eq!(realm.run(setup), Ok(JsValue::Bool(true)));
realm.set_es2015(true);
let check = "Math.max.name === 'max' && Math.min.name === 'mine' && \
Object.getOwnPropertyDescriptor(Math.min, 'length').configurable";
assert_eq!(realm.run(check), Ok(JsValue::Bool(true)));
}
#[test]
fn frozen_built_ins_keep_their_properties_when_the_names_are_set() {
let mut realm = Realm::new();
assert_eq!(realm.run("var f = Object.freeze(Math.max), g = Object.preventExtensions(Math.min); true"), Ok(JsValue::Bool(true)));
realm.set_es2015(true);
let check = "f === Math.max && Object.isFrozen(f) && !f.hasOwnProperty('name') && \
!Object.getOwnPropertyDescriptor(f, 'length').configurable && \
!g.hasOwnProperty('name') && !Object.getOwnPropertyDescriptor(g, 'length').configurable && \
Math.abs.name === 'abs'";
assert_eq!(realm.run(check), Ok(JsValue::Bool(true)));
realm.set_es2015(false);
assert_eq!(realm.run("Object.isFrozen(Math.max) && !Math.max.hasOwnProperty('name')"), Ok(JsValue::Bool(true)));
}
#[test]
fn built_in_names_that_do_not_fit_the_heap_end_the_run_and_wait_for_room() {
let mut realm = Realm::new();
let used = realm.interp().heap.bytes;
realm.set_limits(Limits { heap_bytes: used + 4096, ..Limits::default() });
realm.set_es2015(true);
let e = realm.run("1").unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{e:?}");
assert!(realm.interp().heap.bytes <= used + 4096);
realm.set_limits(Limits::default());
assert_eq!(realm.run("Math.max.name === 'max' && Function.prototype.name === ''"), Ok(JsValue::Bool(true)));
}
#[test]
fn a_new_realm_names_the_built_ins_under_its_own_heap_limit() {
let used = es().interp().heap.bytes;
let limits = Limits { heap_bytes: used + 4096, ..Limits::default() };
let mut realm = Realm::with_options(es_options(), limits);
assert_eq!(realm.interp().heap.bytes, used);
let e = realm.run("1").unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{e:?}");
assert!(realm.interp().heap.bytes <= used + 4096);
realm.set_limits(Limits::default());
assert_eq!(realm.run("Math.max.name === 'max' && Function.prototype.name === ''"), Ok(JsValue::Bool(true)));
}
// ---- function names ----
#[test]
fn declarations_and_expressions_have_their_own_name() {
truth(&name_is("function () {}", ""));
truth(&format!("function decl() {{}} {}", name_is("decl", "decl")));
truth(&name_is("function expr() {}", "expr"));
truth(&name_is("() => {}", ""));
truth("var g = function inner() { return inner; }; g() === g && g.name === 'inner'");
truth(&name_is("Function('a', 'return a')", "anonymous"));
truth(&name_is("new Function()", "anonymous"));
truth("Object.getOwnPropertyNames(function f() {}).slice(0, 2).join() === 'length,name'");
}
#[test]
fn an_anonymous_function_takes_the_name_it_is_first_bound_to() {
truth(&format!("var v = function () {{}}; {}", name_is("v", "v")));
truth(&format!("let l = () => {{}}; {}", name_is("l", "l")));
truth(&format!("const c = (function () {{}}); {}", name_is("c", "c")));
truth(&format!("var a; a = () => 1; {}", name_is("a", "a")));
truth(&format!("var a, b; a = b = function () {{}}; {}", name_is("b", "b")));
truth(&format!("function f(p = () => {{}}) {{ return p; }} {}", name_is("f()", "p")));
truth("function f(p = () => {}) { return p; } var given = (0, function () {}); f(given) === given && given.name === ''");
// A function that already has a name, a function in a comma expression, a parenthesized
// target and a property target keep the name they have.
truth("var n = function m() {}; n.name === 'm'");
truth("var s = (0, function () {}); s.name === ''");
truth("var t; (t) = function () {}; t.name === ''");
truth("var o = {}; o.p = function () {}; o.p.name === ''");
truth("var q; q += function () {}; typeof q === 'string'");
}
#[test]
fn object_literal_functions_are_named_after_their_property() {
truth(&name_is("({ p: function () {} }).p", "p"));
truth(&name_is("({ 'str key': () => {} })['str key']", "str key"));
truth(&name_is("({ 1.5: () => {} })['1.5']", "1.5"));
truth(&name_is("({ m() {} }).m", "m"));
truth(&name_is("({ ['c' + 'k']: function () {} }).ck", "ck"));
truth(&name_is("({ [1 + 1]() {} })[2]", "2"));
truth(&name_is("Object.getOwnPropertyDescriptor({ get g() {} }, 'g').get", "get g"));
truth(&name_is("Object.getOwnPropertyDescriptor({ set s(v) {} }, 's').set", "set s"));
truth(&name_is("Object.getOwnPropertyDescriptor({ get ['x' + 1]() {} }, 'x1').get", "get x1"));
truth(&name_is("Object.getOwnPropertyDescriptor({ set ['x' + 1](v) {} }, 'x1').set", "set x1"));
truth("var o = { p: function named() {} }; o.p.name === 'named'");
truth("var f = function () {}; var o = { f }; o.f.name === 'f' && ({ g: f }).g.name === 'f'");
truth("var o = { xs: (0, function () {}) }; o.xs.name === ''");
}
#[test]
fn symbol_keys_name_functions_after_their_description() {
truth(&format!("var s = Symbol('s'); var o = {{ [s]: () => 0 }}; {}", name_is("o[s]", "[s]")));
truth(&format!("var s = Symbol(''); var o = {{ [s]() {{}} }}; {}", name_is("o[s]", "[]")));
truth(&format!("var e = Symbol(); var o = {{ [e]: function () {{}} }}; {}", name_is("o[e]", "")));
let accessors = |key: &str| format!("var k = {key}; var d = Object.getOwnPropertyDescriptor({{ get [k]() {{}}, set [k](v) {{}} }}, k);");
truth(&format!("{} {} && {}", accessors("Symbol('a')"), name_is("d.get", "get [a]"), name_is("d.set", "set [a]")));
truth(&format!("{} {} && {}", accessors("Symbol()"), name_is("d.get", "get "), name_is("d.set", "set ")));
truth(&format!("var o = {{ [Symbol.iterator]() {{}} }}; {}", name_is("o[Symbol.iterator]", "[Symbol.iterator]")));
}
#[test]
fn a_default_value_takes_the_name_of_its_target() {
truth(&format!("var {{ a = function () {{}} }} = {{}}; {}", name_is("a", "a")));
truth(&format!("let [b = () => 0] = []; {}", name_is("b", "b")));
truth(&format!("const {{ x: y = function () {{}} }} = {{}}; {}", name_is("y", "y")));
truth(&format!("var c; ({{ c = function () {{}} }} = {{}}); {}", name_is("c", "c")));
truth(&format!("var d; [d = () => 0] = []; {}", name_is("d", "d")));
truth(&format!("var e; ({{ k: e = function () {{}} }} = {{}}); {}", name_is("e", "e")));
truth(&format!("function f({{ p = () => 0 }}) {{ return p; }} {}", name_is("f({})", "p")));
truth(&format!("var got; for (const [q = function () {{}}] of [[]]) got = q; {}", name_is("got", "q")));
truth(&format!("var got; try {{ throw {{}}; }} catch ({{ r = () => 0 }}) {{ got = r; }} {}", name_is("got", "r")));
// A parenthesized or property target, a function with its own name and a value that is
// given keep the names they have.
truth("var t; [(t) = function () {}] = []; t.name === ''");
truth("var o = {}; [o.p = function () {}] = []; o.p.name === ''");
truth("var { g = function h() {} } = {}; g.name === 'h'");
truth("var given = (0, function () {}); var { k = function () {} } = { k: given }; k === given && k.name === ''");
}
#[test]
fn bound_and_built_in_functions_have_names() {
truth(&name_is("function target() {}.bind()", "bound target"));
truth(&name_is("function target() {}.bind().bind()", "bound bound target"));
truth(&name_is("Object.defineProperty(function () {}, 'name', { value: 7 }).bind()", "bound "));
throws("Object.defineProperty(function () {}, 'name', { get() { throw new RangeError('name'); } }).bind()", "RangeError");
truth(&name_is("Array.prototype.map", "map"));
truth(&name_is("Object", "Object"));
truth(&name_is("Function.prototype", ""));
truth(&name_is("Function.prototype.bind", "bind"));
truth("Object.getOwnPropertyNames(Function).slice(0, 2).join() === 'length,name'");
}
#[test]
fn bind_reads_only_an_own_length() {
truth(
"var read = 0; function t(a, b) {} delete t.length; \
Object.defineProperty(Function.prototype, 'length', { get: function () { read++; return 5; }, configurable: true }); \
var b = t.bind(); read === 0 && b.length === 0",
);
truth("function t(a, b) {} t.bind(null, 1).length === 1");
}
#[test]
fn bind_charges_fuel_for_a_long_name() {
let mut realm = es();
let setup = "var s = 'x'; for (var i = 0; i < 20; i++) s += s; function t() {} function u() {} \
Object.defineProperty(t, 'name', { value: s }); true";
assert_eq!(realm.run(setup), Ok(JsValue::Bool(true)));
realm.set_limits(Limits { fuel: 10_000, ..Limits::default() });
assert_eq!(realm.run("u.bind().name === 'bound u'"), Ok(JsValue::Bool(true)));
let e = realm.run("t.bind(); true").unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel), "{e:?}");
}
#[test]
fn function_lengths_can_be_redefined() {
truth("function f(a, b) {} delete f.length && !f.hasOwnProperty('length')");
truth("var g = (a) => a; Object.defineProperty(g, 'length', { value: 5 }); g.length === 5");
truth("function t(a, b) {} var b = t.bind(); Object.getOwnPropertyDescriptor(b, 'length').configurable");
truth("delete Math.max.length && Math.max.hasOwnProperty('length') === false");
}
// ---- the language mode ----
#[test]
fn without_the_option_the_new_forms_are_syntax_errors() {
for options in [Options::default(), Options { e4x: true, ..Options::default() }] {
for src in ["var a = 1; ({ a })", "({ [1]: 2 })", "({ m() {} })", "({ get [a]() {} })", "({ a = 1 })"] {
let r = Realm::with_options(options.clone(), Limits::default()).run(src);
assert!(matches!(r, Err(RunError { kind: RunErrorKind::Syntax, .. })), "{src}: {r:?}");
}
}
}
#[test]
fn without_the_option_functions_keep_their_names_and_lengths() {
for options in [Options::default(), Options { e4x: true, ..Options::default() }] {
let mut realm = Realm::with_options(options, Limits::default());
let src = "function f(a) {} var v = function () {}; var o = { p: function () {}, __proto__: null }; \
!f.hasOwnProperty('name') && !v.hasOwnProperty('name') && !o.p.hasOwnProperty('name') && \
!Object.hasOwnProperty('name') && !Function.prototype.bind.hasOwnProperty('name') && \
!f.bind().hasOwnProperty('name') && !(delete f.length) && f.hasOwnProperty('length') && \
!Object.getOwnPropertyDescriptor(Math.max, 'length').configurable && o.hasOwnProperty('__proto__') && \
({ __proto__: 1, __proto__: 2 }).__proto__ === 2 && f.hasOwnProperty('prototype') && \
Object.getOwnPropertyDescriptor({ get g() {} }, 'g').get.hasOwnProperty('prototype')";
assert_eq!(realm.run(src), Ok(JsValue::Bool(true)));
}
}
#[test]
fn turning_the_option_on_names_the_built_ins_once() {
let mut realm = Realm::new();
assert_eq!(realm.run("Array.prototype.map.hasOwnProperty('name')"), Ok(JsValue::Bool(false)));
realm.set_es2015(true);
assert_eq!(
realm.run("Array.prototype.map.name === 'map' && Object.getOwnPropertyDescriptor(Math.max, 'length').configurable"),
Ok(JsValue::Bool(true))
);
// The built-ins keep the names after it is turned off; the code read then gets none.
realm.set_es2015(false);
assert_eq!(realm.run("Array.prototype.map.name === 'map' && !(function f() {}).hasOwnProperty('name')"), Ok(JsValue::Bool(true)));
}
// ---- robustness ----
const FRAGMENTS: &[&str] = &[
"({",
"})",
"{",
"}",
"[",
"]",
"(",
")",
",",
":",
";",
"a",
"b",
"get ",
"set ",
"__proto__",
"'k'",
"1",
"=",
"=>",
"function ",
"...",
"this",
"x",
"+",
" ",
"\n",
"'use strict';",
"var ",
"let ",
];
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
#[test]
fn arbitrary_object_literal_programs_never_panic(parts in proptest::collection::vec(0..FRAGMENTS.len(), 0..60)) {
let src: String = parts.iter().map(|&i| FRAGMENTS[i]).collect();
let mut realm = Realm::with_options(es_options(), Limits { fuel: 20_000, heap_bytes: 1 << 20, frames: 200, reentry: 8 });
if let Err(e) = realm.run(&src) {
prop_assert!(e.kind != RunErrorKind::Internal, "{src:?}: {e:?}");
}
}
}
+514 -42
View File
@@ -93,7 +93,10 @@ fn redeclarations_and_bad_declarations_are_syntax_errors() {
syntax("try {} catch (e) { let e; }");
syntax("const c;");
syntax("let let = 1;");
syntax("let [a] = [1];");
syntax("let [a];");
syntax("let [let] = [1];");
syntax("let [a, a] = [1, 2];");
syntax("try {} catch ([e]) { let e; }");
syntax("'use strict'; { function f() {} function f() {} }");
syntax("for (let x = 1 in {}) {}");
syntax("if (1) let x = 1;");
@@ -170,6 +173,20 @@ fn global_lexical_bindings_stay_across_runs_and_cannot_be_redeclared() {
assert!(restricted.is_err(), "{restricted:?}");
}
#[test]
fn a_var_an_inherited_property_satisfied_does_not_stop_a_later_let() {
let mut realm = Realm::new();
assert_eq!(realm.run("Object.prototype.x = 1; true"), Ok(JsValue::Bool(true)));
let first = realm.run("var x; delete Object.prototype.x && !this.hasOwnProperty('x')");
assert_eq!(first, Ok(JsValue::Bool(true)));
realm.set_es2015(true);
assert_eq!(realm.run("let x = 2; x"), Ok(JsValue::Number(2.0)));
// A `var` that made an own property still stops one.
assert_eq!(realm.run("var y; true"), Ok(JsValue::Bool(true)));
let again = realm.run("let y = 1;");
assert!(matches!(&again, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("SyntaxError")), "{again:?}");
}
#[test]
fn a_script_stopped_at_the_heap_limit_declares_no_global_lexical_name() {
// The `let` names and the variables each fit in the heap at some limits, but not together.
@@ -537,14 +554,16 @@ fn rest_parameters_collect_the_remaining_arguments() {
// ---- spread ----
#[test]
fn spread_expands_arrays_strings_and_array_like_objects() {
fn spread_expands_what_an_iterator_gives() {
truth("var a = [1, 2]; var b = [0, ...a, 3]; b.join() === '0,1,2,3' && b.length === 4");
truth("var b = [...'a\\uD83D\\uDE00b']; b.length === 3 && b[1] === '\\uD83D\\uDE00'");
truth("var b = [...{ length: 2, 0: 'x', 1: 'y' }]; b.join() === 'x,y'");
// A negative, NaN or fractional length is read as ToLength reads it.
truth("[...{ length: -1, 0: 'x' }].length === 0 && [...{ length: NaN }].length === 0");
truth("var b = [...{ length: 1.9, 0: 'x', 1: 'y' }]; b.join() === 'x'");
truth("function f() { return arguments.length; } f(...{ length: -4294967295, 0: 1 }) === 0");
truth("function f() { return [...arguments]; } f(1, 2).join() === '1,2'");
// Any object with an @@iterator method spreads, in the order its iterator gives.
truth(
"var n = 0; var it = { [Symbol.iterator]: function () { return { next: function () { n++; return { value: n, done: n > 3 }; } }; } }; \
var b = [...it]; b.join() === '1,2,3' && n === 4",
);
truth("var a = [1, 2]; a[Symbol.iterator] = function () { return [9][Symbol.iterator](); }; [...a].join() === '9'");
truth("var b = [...[1, , 3]]; b.length === 3 && 1 in b && b[1] === undefined");
truth("var b = [, ...[1]]; b.length === 2 && !(0 in b)");
truth("function f() { return arguments.length; } f(...[1, 2], 3, ...[]) === 3");
@@ -571,8 +590,8 @@ fn spread_reads_an_array_s_length_again_before_each_element() {
let grow = "var a = [1]; Object.defineProperty(a, 0, { get: function () { a.push(2); return 'v'; } }); \
var b = [...a]; b.join() === 'v,2'";
truth(grow);
// An object that is not an array keeps the length it had when spread began.
truth("var o = { length: 2, get 0() { o.length = 1; return 'v'; }, 1: 'w' }; [...o].join() === 'v,w'");
// An object without an iterator is not spread by its length.
throws("var o = { length: 2, 0: 'v', 1: 'w' }; [...o];", "TypeError");
}
#[test]
@@ -585,36 +604,41 @@ fn an_array_s_spread_is_checked_against_the_elements_it_reads() {
let then_more = "var a = []; a.length = 4294967295; Object.defineProperty(a, 0, { get: function () { a.length = 1; return 7; } }); \
var b = [...a, ...[1, 2]]; b.join() === '7,1,2'";
truth(then_more);
// An array no getter reads is checked when spread begins, without reading its elements.
// An array's iterator steps through every index, so a long array ends at the fuel limit.
let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() });
let long = realm.run("var a = []; a.length = 4294967295; [...a]");
assert!(is_thrown(&long, "RangeError"), "{long:?}");
// An object that is not an array is still checked against the length it has when spread
// begins.
throws("[0, ...{ length: 4294967295 }];", "RangeError");
assert!(matches!(&long, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Fuel)), "{long:?}");
// An object without an iterator is not spread by its length.
throws("[0, ...{ length: 4294967295 }];", "TypeError");
}
#[test]
fn an_index_setter_without_a_getter_does_not_delay_the_spread_s_check() {
// A setter does not run when the elements are read, so the array is still checked when
// spread begins, on its own and on its prototype.
fn an_index_setter_without_a_getter_does_not_run_when_the_array_is_spread() {
// The iterator reads the element and the new array defines its own, so a setter on the array
// or on its prototype does not run, and the long array ends at the fuel limit.
for setter in ["a", "Array.prototype"] {
let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() });
let src = format!("var a = []; a.length = 4294967295; Object.defineProperty({setter}, 0, {{ set: function () {{}} }}); [...a]");
let src = format!(
"var ran = false; var a = []; a.length = 4294967295; Object.defineProperty({setter}, 0, {{ set: function () {{ ran = true; }} }}); [...a]"
);
let long = realm.run(&src);
assert!(is_thrown(&long, "RangeError"), "{setter}: {long:?}");
assert!(matches!(&long, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Fuel)), "{setter}: {long:?}");
realm.set_limits(Limits::default());
assert_eq!(realm.run("ran"), Ok(JsValue::Bool(false)), "{setter}");
}
}
#[test]
fn a_prototype_getter_behind_an_own_element_does_not_delay_the_spread_s_check() {
// The array's own element 0 is read instead of the getter on its prototype, so no getter can
// shrink it, and it is checked when spread begins.
fn a_prototype_getter_behind_an_own_element_is_not_read_by_the_spread() {
// The array's own element 0 is read instead of the getter on its prototype, so the getter does
// not shrink it, and the long array ends at the fuel limit.
let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() });
let src = "var a = [7]; Object.defineProperty(Array.prototype, 0, { get: function () { a.length = 1; return 0; } }); \
a.length = 4294967295; [...a]";
let long = realm.run(src);
assert!(is_thrown(&long, "RangeError"), "{long:?}");
assert!(matches!(&long, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Fuel)), "{long:?}");
realm.set_limits(Limits::default());
assert_eq!(realm.run("a.length"), Ok(JsValue::Number(4294967295.0)));
// A getter on the prototype with no own element in front of it is read, and shrinks the array.
let shrink = "var a = []; a.length = 4294967295; \
Object.defineProperty(Array.prototype, 0, { get: function () { a.length = 1; return 7; } }); \
@@ -622,20 +646,6 @@ fn a_prototype_getter_behind_an_own_element_does_not_delay_the_spread_s_check()
truth(shrink);
}
#[test]
fn looking_for_index_getters_takes_fuel_for_each_property() {
// Each attempt to spread the long array looks at every one of its 10,000 elements, so each
// takes at least that much fuel.
let fuel = 10_000_000;
let mut realm = Realm::with_options(es_options(), Limits { fuel, ..Limits::default() });
let setup = "var a = []; for (var i = 0; i < 10000; i++) a[i] = i; a.length = 4294967295; 0";
assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0)));
let attempt = "var ok = false; try { [...a]; } catch (e) { ok = e instanceof RangeError; } ok";
assert_eq!(realm.run(attempt), Ok(JsValue::Bool(true)));
let used = fuel - realm.interp().fuel;
assert!(used >= 10_000, "{used}");
}
#[test]
fn spread_counts_each_index_name_against_the_heap() {
// The elements' properties, with their index names and a string's characters, fit in the
@@ -704,20 +714,82 @@ fn spreading_other_values_is_a_type_error() {
throws("[...null];", "TypeError");
throws("[...undefined];", "TypeError");
throws("[...{}];", "TypeError");
// An object with a length is not iterable for that.
throws("[...{ length: 2, 0: 'x', 1: 'y' }];", "TypeError");
throws("[...{ [Symbol.iterator]: function () { return 1; } }];", "TypeError");
throws("[...{ [Symbol.iterator]: function () { return { next: function () { return 1; } }; } }];", "TypeError");
throws("Math.max(...true);", "TypeError");
throws("new Array(...{ a: 1 });", "TypeError");
}
/// Runs `setup`, which gives `true`, and collects its garbage, then `call` once to measure the
/// bytes it adds. Then, for every room from none to one byte less than that, in steps of 8
/// bytes, it runs `call` in a new realm with that room: the run ends with the heap limit or a
/// collection makes room, and the heap does not pass the limit either way.
fn stays_within_every_limit(setup: &str, call: &str) {
let ready = || {
let mut realm = es();
assert_eq!(realm.run(setup), Ok(JsValue::Bool(true)), "{setup}");
realm.collect_garbage();
realm
};
let mut realm = ready();
let before = realm.interp().heap.bytes;
assert!(realm.run(call).is_ok(), "{call}");
let added = realm.interp().heap.bytes.saturating_sub(before);
for room in (0..added).rev().step_by(8) {
let mut realm = ready();
let limit = realm.interp().heap.bytes + room;
realm.set_limits(Limits { heap_bytes: limit, ..Limits::default() });
let r = realm.run(call);
let used = realm.interp().heap.bytes;
assert!(r.is_ok() || matches!(&r, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)), "{call} with {room}: {r:?}");
assert!(used <= limit, "{call} with {room}: {used} of {limit}");
}
}
#[test]
fn iterator_results_and_template_objects_stay_within_the_heap_limit() {
stays_within_every_limit("var it = [1, 2][Symbol.iterator](), r; true", "r = it.next(); true");
stays_within_every_limit("var it = [][Symbol.iterator](), r; true", "r = it.next(); true");
let parts = (0..60).map(|i| format!("part{i}${{{i}}}")).collect::<String>();
stays_within_every_limit(&format!("var r; function tag(s) {{ return s; }} function go() {{ r = tag`{parts}end`; return true; }} true"), "go()");
}
#[test]
fn declarations_stay_within_the_heap_limit() {
let lets = (0..40).map(|i| format!("let a_long_global_lexical_name_{i} = {i};")).collect::<String>();
stays_within_every_limit("true", &format!("{lets} const fixed = 1; true"));
let body = (0..30).map(|i| format!("let a_long_body_lexical_name_{i} = {i}; function a_long_body_function_name_{i}() {{}}")).collect::<String>();
stays_within_every_limit(&format!("function f(a = 1) {{ {body} return true; }} true"), "f()");
}
#[test]
fn code_stopped_by_the_frame_limit_declares_nothing() {
let mut realm = es();
realm.set_limits(Limits { frames: 0, ..Limits::default() });
let e = realm.run("let kept = 1; var also = 2;").unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Frames), "{e:?}");
realm.set_limits(Limits { frames: 1, ..Limits::default() });
let e = realm.run("eval('var leaked = 1; let inner = 2;')").unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Frames), "{e:?}");
realm.set_limits(Limits::default());
assert_eq!(realm.run("let kept = 3; typeof also === 'undefined' && typeof leaked === 'undefined' && kept === 3"), Ok(JsValue::Bool(true)));
}
#[test]
fn spread_and_templates_stay_within_the_limits() {
let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() });
let e = realm.run("[...{ length: 4294967294 }]").unwrap_err();
let endless = "{ [Symbol.iterator]: function () { return { next: function () { return { value: 1, done: false }; } }; } }";
let e = realm.run(&format!("[...{endless}]")).unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel), "{e:?}");
let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() });
let e = realm.run("var a = []; a.length = 4294967294; [0, ...a];").unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel), "{e:?}");
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes: 4 << 20, ..Limits::default() });
let e = realm.run("var s = 'x'; for (var i = 0; i < 22; i++) s += s; [...s]").unwrap_err();
assert!(matches!(e.kind, RunErrorKind::Limit(_)), "{e:?}");
throws("function f() {} f(...{ length: 100000 });", "RangeError");
throws("var a = []; a.length = 4294967294; [0, ...a];", "RangeError");
throws("function f() {} var a = []; a.length = 100000; f(...a);", "RangeError");
}
#[test]
@@ -729,9 +801,14 @@ fn spreading_a_rope_counts_its_flattened_length_first() {
let build = "var s = 'x'; for (var i = 0; i < 18; i++) s = s + s; function f(c) { return s + c; } \
function mk() { var a = f('a'); a[0]; return a + 'b'; }";
let limits = Limits { heap_bytes: 4 * 262_146, fuel: 20_000, ..Limits::default() };
for spread in ["[...mk()]", "Math.max(...mk())"] {
for spread in ["[...mk()]", "Math.max(...mk())", "var [c] = mk()", "for (var c of mk()) break"] {
let e = Realm::with_options(es_options(), limits.clone()).run(&format!("{build} {spread}; 0")).unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{spread}: {e:?}");
// A realm without `Symbol.iterator` walks the string, and flattens it the same way.
let mut walking = Realm::with_options(Options::default(), limits.clone());
walking.set_es2015(true);
let e = walking.run(&format!("{build} {spread}; 0")).unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "walking {spread}: {e:?}");
}
let made = Realm::with_options(es_options(), limits).run(&format!("{build} mk(); 0"));
assert_eq!(made, Ok(JsValue::Number(0.0)), "the rope is made within the fuel");
@@ -946,13 +1023,406 @@ fn for_each_takes_let_and_const_with_e4x() {
assert_eq!(e.kind, RunErrorKind::Syntax, "{e:?}");
}
#[test]
fn for_each_takes_an_assignment_pattern_with_e4x() {
let mut realm = Realm::with_options(Options { e4x: true, ..es_options() }, Limits::default());
let src = "var x, y; for each ([x] in { a: [7] }); for each ({ p: y } in [{ p: 8 }]); x + y";
assert_eq!(realm.run(src), Ok(JsValue::Number(15.0)));
let legacy = Realm::with_options(Options { e4x: true, ..Options::default() }, Limits::default()).run("var x; for each ([x] in {});");
assert!(matches!(&legacy, Err(e) if e.kind == RunErrorKind::Syntax), "{legacy:?}");
}
// ---- for-of and destructuring ----
/// An iterable whose iterator gives 1 to `n` and counts the calls to its `return` method in
/// `closed`.
const COUNTED: &str = "var closed = 0; function it(n) { var i = 0; return { [Symbol.iterator]: function () { return this; }, \
next: function () { i++; return { value: i, done: i > n }; }, return: function () { closed++; return {}; } }; } ";
fn counted(src: &str) {
truth(&format!("{COUNTED}{src}"));
}
#[test]
fn for_of_runs_the_body_for_each_value() {
truth("var s = ''; for (var x of ['a', 'b']) s += x; s === 'ab' && x === 'b'");
truth("var s = []; for (var c of 'a\\uD83D\\uDE00') s.push(c); s.length === 2 && s[1] === '\\uD83D\\uDE00'");
truth("var n = 0; for (var x of []) n++; n === 0");
truth("var o = {}; for (o.p of [1, 2]); o.p === 2");
truth("var r = []; for (var [a, b] of [[1, 2], [3, 4]]) r.push(a + b); r.join() === '3,7'");
truth("var a, b; for ([a, { b }] of [[1, { b: 2 }]]); a === 1 && b === 2");
truth("var r = []; outer: for (var i = 0; i < 2; i++) { for (var x of [1, 2]) { if (x === 2) continue outer; r.push(i); } } r.join() === '0,1'");
truth("var s = 0; for (var x of [1, 2, 3]) { if (x === 2) continue; s += x; } s === 4");
truth("eval('1; for (var x of []) {}') === undefined && eval('1; for (var x of [2]) { break; }') === undefined");
truth("eval('1; for (var x of [2, 3]) { x; }') === 3");
}
#[test]
fn loops_whose_body_never_completes_give_undefined() {
for src in [
"42; for (let i = 0; i < 0; i++) {}",
"42; for (const k in {}) {}",
"42; for (let k in {}) {}",
"42; for (var i = 0; i < 0; i++) {}",
"42; for (var k in {}) {}",
"42; while (false) {}",
"42; do { break; } while (true)",
] {
assert_eq!(es().run(src), Ok(JsValue::Undefined), "{src}");
}
assert_eq!(es().run("42; for (let i = 0; i < 2; i++) { i; }"), Ok(JsValue::Number(1.0)));
assert_eq!(es().run("42; for (let k in { a: 1 }) { k; }"), Ok(JsValue::String("a".into())));
// ECMAScript 5.1 code keeps the value before the loop.
assert_eq!(Realm::new().run("42; for (var i = 0; i < 0; i++) {}"), Ok(JsValue::Number(42.0)));
assert_eq!(Realm::new().run("42; while (false) {}"), Ok(JsValue::Number(42.0)));
}
#[test]
fn if_switch_with_and_try_without_a_value_give_undefined() {
for src in [
"for (let i = 0; i < 2; i++) { if (i === 0) 7; }",
"42; if (false) 7;",
"42; if (true) {}",
"42; switch (1) { case 2: 7; }",
"42; with ({}) {}",
"42; try {} finally {}",
"42; try { 7; throw 1; } catch (e) {}",
"42; do { 7; if (true) break; } while (false)",
] {
assert_eq!(es().run(src), Ok(JsValue::Undefined), "{src}");
assert_eq!(es().run(&format!("eval({src:?})")), Ok(JsValue::Undefined), "{src}");
}
assert_eq!(es().run("42; ;"), Ok(JsValue::Number(42.0)));
assert_eq!(es().run("42; if (true) 7;"), Ok(JsValue::Number(7.0)));
assert_eq!(es().run("42; try { 7; } catch (e) {}"), Ok(JsValue::Number(7.0)));
// ECMAScript 5.1 code keeps the earlier value.
assert_eq!(Realm::new().run("42; if (false) 7;"), Ok(JsValue::Number(42.0)));
assert_eq!(Realm::new().run("42; try { 7; throw 1; } catch (e) {}"), Ok(JsValue::Number(7.0)));
}
#[test]
fn for_of_let_and_const_get_a_binding_for_each_iteration() {
truth("var fs = []; for (let x of [1, 2]) fs.push(function () { return x; }); fs[0]() === 1 && fs[1]() === 2");
truth("var fs = []; for (const [k, v] of [[1, 2], [3, 4]]) fs.push(() => k + v); fs[0]() === 3 && fs[1]() === 7");
truth("for (let x of [1]) {} typeof x === 'undefined'");
throws("for (const x of [1]) x = 2;", "TypeError");
// The iterable is read where the head's names are not yet initialized.
throws("let x = [1]; for (let x of x) {}", "ReferenceError");
}
#[test]
fn for_of_closes_the_iterator_when_the_loop_is_left_early() {
counted("for (var x of it(5)) break; closed === 1 && x === 1");
counted("function f() { for (var x of it(5)) return x * 10; } f() === 10 && closed === 1");
counted("try { for (var x of it(5)) throw 1; } catch (e) {} closed === 1");
counted("outer: for (var i = 0; i < 2; i++) for (var x of it(5)) continue outer; closed === 2");
counted("for (var x of it(5)) for (var y of it(5)) break; closed === 5");
counted("try { for (var x of it(5)) { try { break; } finally { closed += 10; } } } finally {} closed === 11");
counted(
"var t = it(5); t.next = function () { return { value: [], done: false }; }; \
var r; try { for (var [a = (function () { throw 7; })()] of t); } catch (e) { r = e; } r === 7 && closed === 1",
);
// An iterator that finishes, or whose own next method throws, is not closed.
counted("for (var x of it(2)); closed === 0");
counted("var t = it(5); t.next = function () { throw 3; }; try { for (var x of t); } catch (e) {} closed === 0");
// Nor is one whose result's `value` getter throws (sections 13.7.5.13 and 13.3.3.6).
let bad_value = "var t = it(5); t.next = function () { return { done: false, get value() { throw 4; } }; };";
counted(&format!("{bad_value} var r; try {{ for (var x of t); }} catch (e) {{ r = e; }} r === 4 && closed === 0"));
counted(&format!("{bad_value} var r; try {{ var [a] = t; }} catch (e) {{ r = e; }} r === 4 && closed === 0"));
}
#[test]
fn closing_an_iterator_reports_a_bad_return_unless_an_exception_is_on_its_way() {
let bad = "var bad = { [Symbol.iterator]: function () { return this; }, next: function () { return { value: 1, done: false }; }, \
return: function () { return 1; } }; ";
throws(&format!("{bad} for (var x of bad) break;"), "TypeError");
truth(&format!("{bad} var r; try {{ for (var x of bad) throw new RangeError('x'); }} catch (e) {{ r = e; }} r instanceof RangeError"));
let throwing = "var t = { [Symbol.iterator]: function () { return this; }, next: function () { return { value: 1, done: false }; }, \
return: function () { throw new SyntaxError('r'); } }; ";
throws(&format!("{throwing} for (var x of t) break;"), "SyntaxError");
truth(&format!("{throwing} var r; try {{ for (var x of t) throw 5; }} catch (e) {{ r = e; }} r === 5"));
// A close that throws when `return` or a jump to an outer statement leaves the loop reaches
// the enclosing catch clause. Inner iterators are closed first, and a throwing inner close
// still closes the outer iterators.
let caught = |src: &str| format!("{COUNTED}{throwing} var r; try {{ {src} }} catch (e) {{ r = e; }} r instanceof SyntaxError");
for src in [
"(function () { for (var x of t) return 1; })();",
"(function () { for (var x of [1]) for (var y of t) return 1; })();",
"outer: for (var i = 0; i < 2; i++) for (var x of t) continue outer;",
"outer: for (var x of t) for (var y of [1, 2]) break outer;",
"outer: for (var x of t) for (var y of it(5)) for (var z of it(5)) break outer;",
] {
truth(&format!("{} && closed === {}", caught(src), src.matches("it(5)").count()));
}
truth(&format!("{} && closed === 1", caught("outer: for (var x of it(5)) for (var y of t) break outer;")));
truth(&format!("{} && closed === 1", caught("(function () { for (var x of it(5)) for (var y of t) return 1; })();")));
}
#[test]
fn an_exception_that_closes_an_iterator_keeps_where_it_was_thrown() {
let src = "var t = { [Symbol.iterator]: function () { return this; }, next: function () { return { value: 1, done: false }; }, \
return: function () { return {}; } };\nfor (var x of t) {\n if (x) throw 1;\n x = String(x);\n}";
// A collection runs at each reservation, so one runs while `return` is called.
let mut realm = es();
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true));
let r = realm.run(src);
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false));
let e = r.unwrap_err();
assert_eq!((&e.kind, e.line, e.column), (&RunErrorKind::Thrown, 3, 10), "{e:?}");
// A `return` getter that throws does not replace the exception (ECMA-262 2023 section 7.4.8).
truth(
"var t = { [Symbol.iterator]: function () { return this; }, next: function () { return { value: 1, done: false }; }, \
get return() { throw 2; } }; var r; try { for (var x of t) throw 1; } catch (e) { r = e; } r === 1",
);
}
#[test]
fn array_patterns_step_the_iterator_and_close_it() {
truth("var [a, , b = 3, ...c] = [1, 2, undefined, 4, 5]; a === 1 && b === 3 && c.join() === '4,5'");
truth("var [a, b] = 'xy'; a + b === 'xy'");
truth("var [a, b] = [1]; a === 1 && b === undefined");
truth("let [[a], [b]] = [[1], [2]]; a + b === 3");
truth("var [...[a, b]] = [1, 2]; a + b === 3");
counted("var [a] = it(5); closed === 1 && a === 1");
counted("var [a, ...r] = it(2); closed === 0 && r.join() === '2'");
counted("var [] = it(5); closed === 1");
counted("var [a, b] = it(1); closed === 0 && b === undefined");
// A hole steps the iterator without reading the result's `value`.
let bad_value = "var t = it(5); t.next = function () { return { done: false, get value() { throw 4; } }; };";
counted(&format!("{bad_value} var [,] = t; closed === 1"));
counted(&format!("{bad_value} [,] = t; for (let [,] of [t]); closed === 2"));
counted("try { var [a = (function () { throw 1; })()] = it(0); } catch (e) {} closed === 0");
counted("try { var [a, b = (function () { throw 1; })()] = [1]; } catch (e) {} closed === 0");
counted("var o = { set p(v) { throw 2; } }; try { [o.p] = it(5); } catch (e) {} closed === 1");
throws("var [a] = {};", "TypeError");
throws("var [a] = 1;", "TypeError");
}
#[test]
fn object_patterns_read_properties_by_name() {
truth("let { x, y: z = 2, ['w' + 1]: w } = { x: 1, w1: 4 }; x === 1 && z === 2 && w === 4");
truth("const [{ a: [b] }] = [{ a: [7] }]; b === 7");
truth("var { length } = 'abc'; length === 3");
truth("var s = Symbol(); var { [s]: v } = { [s]: 9 }; v === 9");
truth("var { 0: a, 'b c': b } = { 0: 1, 'b c': 2 }; a + b === 3");
truth(
"var order = []; var o = { get a() { order.push('a'); return 1; }, get b() { order.push('b'); return 2; } }; \
var { b, a } = o; order.join() === 'b,a'",
);
// A `var` pattern's names are resolved before their values are read (sections 13.3.3.6
// and 13.3.3.7).
truth(
"var o = { x: 0 }; var t = { [Symbol.iterator]: function () { return this; }, \
next: function () { delete o.x; return { value: 1, done: false }; }, return: function () { return {}; } }; \
with (o) { var [x] = t; } o.x === 1 && x === undefined",
);
truth("var o = { y: 0 }; with (o) { var { a: y } = { get a() { delete o.y; return 2; } }; } o.y === 2 && y === undefined");
}
#[test]
fn destructuring_assignment_writes_to_any_assignment_target() {
truth("var a = 1, b = 2; [a, b] = [b, a]; a === 2 && b === 1");
truth("var a; var v = [1, 2]; var r = ([a] = v); r === v && a === 1");
truth("var o = {}; [o.a, o['b']] = [1, 2]; ({ c: o.c } = { c: 3 }); o.a + o.b + o.c === 6");
truth("var a, b; ({ a, b = 5 } = { a: 1 }); a === 1 && b === 5");
truth("var x, y; [x = 1, [y] = [2]] = []; x === 1 && y === 2");
truth("var r = []; var a; [a = r.push('default')] = [undefined]; a === 1 && r.length === 1");
}
#[test]
fn destructured_parameters_and_catch_clauses() {
truth("function f([a, b], { c } = { c: 3 }) { return a + b + c; } f([1, 2]) === 6");
truth("(([a], { b }) => a + b)([1], { b: 2 }) === 3");
truth("function f(...[a, b]) { return a + b; } f(1, 2) === 3");
truth("function f(a, [b], c = 1) {} f.length === 2");
truth("function f({ a }, b) {} f.length === 2");
truth("function f([a], b = a) { return b; } f([4]) === 4");
truth("function f({ a }) { var a; return a; } f({ a: 6 }) === 6");
truth("var r; try { throw { m: 'x', d: [1] }; } catch ({ m, d: [n] }) { r = m + n; } r === 'x1'");
truth("var r; try { throw [1, 2]; } catch ([a, b]) { r = function () { return a + b; }; } r() === 3");
// A function in a block is not also made a `var` when that `var` would clash with a
// destructured catch parameter (ECMA-262 11th edition sections B.3.3 and B.3.5).
truth("function g() { try { throw [1]; } catch ([f]) { { function f() {} } } return typeof f; } g() === 'undefined'");
truth("try { throw {}; } catch ({ h }) { { function h() {} } } typeof h === 'undefined'");
truth("function g() { try { throw 1; } catch (f) { { function f() {} } } return typeof f; } g() === 'function'");
throws("function f({ a }) {} f();", "TypeError");
throws("try { throw null; } catch ({ a }) {}", "TypeError");
throws("function f([a], b = a) {} f([]); f(undefined);", "TypeError");
}
#[test]
fn defaults_run_only_for_undefined() {
truth(
"var n = 0; function d() { n++; return 5; } var [a = d()] = [null]; var { b = d() } = { b: 0 }; var [c = d()] = []; \
var { e = d() } = { e: undefined }; a === null && b === 0 && c === 5 && e === 5 && n === 2",
);
truth("var n = 0; function f([a = n++] = [], { b = n++ } = {}) { return a + b; } f([3], { b: 4 }) === 7 && n === 0");
}
#[test]
fn destructuring_undefined_or_null_is_a_type_error() {
throws("var { a } = null;", "TypeError");
throws("var {} = undefined;", "TypeError");
throws("var [a] = null;", "TypeError");
throws("({ a } = undefined);", "TypeError");
throws("for (var { a } of [null]);", "TypeError");
throws("let { a: { b } } = { a: null };", "TypeError");
truth("var { toFixed } = 1; typeof toFixed === 'function'");
}
#[test]
fn object_literals_take_shorthand_and_computed_names() {
truth("var a = 1; var o = { a, ['b' + 1]: 2 }; o.a === 1 && o.b1 === 2");
truth("var s = Symbol('k'); var o = { [s]: 3 }; o[s] === 3 && Object.keys(o).length === 0");
truth("var o = { get ['x' + 1]() { return 4; }, set ['x' + 1](v) { this.y = v; } }; o.x1 = 5; o.x1 === 4 && o.y === 5");
truth("var order = []; var o = { [(order.push(1), 'a')]: order.push(2) }; order.join() === '1,2' && o.a === 2");
}
#[test]
fn bad_patterns_are_syntax_errors() {
for src in [
"({ a = 1 });",
"var o = { a = 1 };",
"[...a, b] = [];",
"[...a,] = [];",
"var [...a, b] = [];",
"({ get a() { return 1; } } = {});",
"([a]) = [];",
"[(a = 1)] = [];",
"[a()] = [];",
"[a + 1] = [];",
"'use strict'; [eval] = [];",
"'use strict'; var { arguments } = {};",
"var [a];",
"const { a };",
"for (var x = 1 of []) ;",
"for (let x = 1 of []) ;",
"for (var [x] = 1 in {}) ;",
"for (x of [], []) ;",
"for (let.x of []) ;",
"for (async of []) ;",
"for (var x of []) let\n[a] = 0;",
"if (1) let [a] = [];",
"for (a() of []) ;",
"function f([a]) { 'use strict'; }",
"function f([a, a]) {}",
"function f(a, [a]) {}",
"([a, a]) => 1;",
"try {} catch ([e, e]) {}",
"try {} catch ([e]) { for (var e of []); }",
"({ a: 1 } = {});",
"[...[a] = []] = [];",
"var a; [a = { b = 1 }] = [];",
"var a; ({ a = { b = 1 } } = {});",
"var a; ({ [{ b = 1 }]: a } = {});",
"for ([a = { b = 1 }] of []) ;",
"(a = { b = 1 }) => 0;",
"([a = { b = 1 }]) => 0;",
] {
syntax(src);
}
// A shorthand property with an initializer is a target only in the pattern that holds it.
truth("var a, b; [{ b = 1 }] = [{}]; ({ a: { b = 2 } = {} } = {}); b === 2");
truth("var f = ({ a = 1 }, [{ b = 2 }] = [{}]) => a + b; f({}) === 3");
// `of` stays a name.
truth("var of = [1]; var n = 0; for (var x of of) n += x; n === 1");
}
#[test]
fn large_patterns_take_their_shorthand_defaults() {
let defaults = (0..20_000).map(|i| format!("a{i} = {i}")).collect::<Vec<_>>().join(", ");
truth(&format!("({{ {defaults} }} = {{}}); a0 === 0 && a19999 === 19999"));
truth(&format!("var f = ({{ {defaults} }}) => a19999; f({{}}) === 19999"));
// A shorthand default inside a default value or a computed name is still an error.
syntax(&format!("({{ {defaults}, b = {{ c = 1 }} }} = {{}});"));
syntax(&format!("({{ [{{ c = 1 }}]: b, {defaults} }} = {{}});"));
let small = "[{ b = 1 }] = [{}]; ".repeat(20_000);
truth(&format!("var b; {small} b === 1"));
syntax(&format!("var b; {small} ({{ c = 1 }});"));
}
#[test]
fn a_realm_without_the_later_built_ins_walks_arrays_arguments_and_strings() {
let mut realm = Realm::new();
realm.set_es2015(true);
let src = "var s = ''; for (var x of [1, 2]) s += x; for (var c of 'a\\uD83D\\uDE00') s += c.length; \
(function () { for (var a of arguments) s += a; })(3); var [p, ...q] = 'xyz'; \
s === '1212' + '3' && [...[4, 5]].length === 2 && p === 'x' && q.join('') === 'yz'";
assert_eq!(realm.run(src), Ok(JsValue::Bool(true)));
let boxed = "var b = new String('ab'); b.toString = function () { return 'cd'; }; \
[...new String('ab')].join() === 'a,b' && [...b].join() === 'c,d'";
assert_eq!(realm.run(boxed), Ok(JsValue::Bool(true)));
let r = realm.run("for (var x of {}) {}");
assert!(matches!(&r, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("TypeError")), "{r:?}");
}
#[test]
fn for_of_and_patterns_stay_within_the_limits() {
let endless = "{ [Symbol.iterator]: function () { return { next: function () { return { value: 1, done: false }; } }; } }";
for src in [format!("for (var x of {endless});"), format!("var [...r] = {endless};")] {
let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() });
let e = realm.run(&src).unwrap_err();
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel), "{src}: {e:?}");
}
// Spread and a rest element reserve each new element's whole size, its index name included,
// so the run ends at the heap limit without passing it, wherever the limit falls. A realm
// without `Symbol.iterator` walks the array by index and makes no result objects.
let walking = |limits: Limits| {
let mut realm = Realm::with_options(Options::default(), limits);
realm.set_es2015(true);
realm
};
let setup = "var a = []; for (var i = 0; i < 2000; i++) a.push(i); 0";
let mut measure = walking(Limits::default());
assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0)));
measure.interp().collect_garbage();
let base = measure.interp().heap.bytes + 100_000;
let mut wrong = Vec::new();
for src in ["var b = [...a]; 0", "var [...b] = a; 0"] {
for heap_bytes in (base..base + 128).step_by(2) {
let mut realm = walking(Limits { heap_bytes, ..Limits::default() });
assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0)));
let r = realm.run(src).map_err(|e| e.kind);
let bytes = realm.interp().heap.bytes;
if r != Err(RunErrorKind::Limit(LimitKind::Heap)) || bytes > heap_bytes {
wrong.push((src, heap_bytes, r, bytes));
}
}
}
assert!(wrong.is_empty(), "runs that ended past the heap limit: {wrong:?}");
// Patterns nested past the nesting limit are a SyntaxError.
for src in [format!("var {}a{} = 1;", "[".repeat(5000), "]".repeat(5000)), format!("({}a{} = 1);", "[".repeat(5000), "]".repeat(5000))] {
let e = es().run(&src).unwrap_err();
assert_eq!(e.kind, RunErrorKind::Syntax, "{e:?}");
}
}
// ---- the language mode ----
#[test]
fn without_the_option_the_new_forms_are_syntax_errors() {
for src in ["let x = 1; x", "const c = 1;", "var f = x => x;", "`t`", "function f(a = 1) {}", "function f(...r) {}", "f(...a)", "[...a]"] {
for src in [
"let x = 1; x",
"const c = 1;",
"var f = x => x;",
"`t`",
"function f(a = 1) {}",
"function f(...r) {}",
"f(...a)",
"[...a]",
"for (var x of []) {}",
"var [a] = [1];",
"var { a } = {};",
"({ a } = {});",
"function f([a]) {}",
"try {} catch ({ a }) {}",
"var o = { ['a']: 1 };",
] {
let r = Realm::new().run(src);
assert!(matches!(r, Err(RunError { kind: RunErrorKind::Syntax, .. })), "{src}: {r:?}");
let extendscript = Options { e4x: true, preprocessor_lines: true, ..Options::default() };
let r = Realm::with_options(extendscript, Limits::default()).run(src);
assert!(matches!(r, Err(RunError { kind: RunErrorKind::Syntax, .. })), "{src}: {r:?}");
}
// `let` stays a name outside strict mode code.
assert_eq!(Realm::new().run("var let = 1; let"), Ok(JsValue::Number(1.0)));
@@ -993,6 +1463,8 @@ fn a_run_keeps_its_language_for_the_code_it_evaluates() {
// ---- robustness ----
const FRAGMENTS: &[&str] = &[
" of ",
"...",
"let ",
"const ",
"var ",
+3 -3
View File
@@ -24,7 +24,7 @@
//! true value for; every entry takes fuel.
use crate::HostItem;
use crate::builtins::{arg, constructor, data, method, native, pausable_method, put_at};
use crate::builtins::{accessor_native, arg, constructor, data, method, native, pausable_method, put_at};
use crate::heap::{CONFIGURABLE, Class, HIDDEN, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, key, string_bytes};
use crate::interp::{Abrupt, ErrorType, Interp, JsResult, Pause};
use crate::value::{Value, index_key};
@@ -1017,10 +1017,10 @@ places!(
/// Defines the accessor `name` on `on`, not enumerable, as the help pages' objects have them.
fn accessor(i: &mut Interp, on: ObjId, name: &'static str, get: NativeFn, set: Option<NativeFn>) -> JsResult<()> {
let g = native(i, name, get, 0, NativeKind::Plain, false)?;
let g = accessor_native(i, "get ", name, get, 0)?;
i.rooted(&[Value::Object(g)], |i| {
let s = match set {
Some(f) => Some(native(i, name, f, 1, NativeKind::Plain, false)?),
Some(f) => Some(accessor_native(i, "set ", name, f, 1)?),
None => None,
};
i.define(on, key(name), Prop::Accessor { get: Some(g), set: s, flags: CONFIGURABLE })
+73 -10
View File
@@ -85,6 +85,16 @@ impl<T> PropMap<T> {
}
}
/// Sets the value under `k` like [`Self::insert`], but puts a new `k` right after `after`
/// when that is there.
pub(crate) fn insert_after(&mut self, after: &[u16], k: Key, v: T) {
let Some(at) = self.position(after).filter(|_| !self.contains(&k)) else { return self.insert(k, v) };
self.entries.insert(at + 1, Some((k, v)));
self.live += 1;
self.index = None;
self.rebuild_index();
}
pub(crate) fn remove(&mut self, k: &[u16]) -> Option<T> {
let i = self.position(k)?;
let (_, v) = self.entries.get_mut(i)?.take()?;
@@ -178,11 +188,12 @@ pub(crate) enum NativeKind {
/// `Data` is a host function given [`crate::Data`], its arguments read as `read` says. `Eval` is a
/// host function that gives source to run as global code ([`crate::HostItem::Evaluator`]); `end`
/// is called when that code ends. `Pausable` is a built-in that may ask the host for a value the
/// run to wait for ([`crate::interp::Pause`]).
/// run to wait for ([`crate::interp::Pause`]). A `Native`'s `prefix` is `get ` or `set ` for a
/// built-in accessor's function and empty otherwise; its ECMAScript 2015 `name` starts with it.
#[derive(Clone)]
pub(crate) enum Func {
Closure { code: Rc<Code>, env: EnvId },
Native { f: NativeFn, kind: NativeKind, constructor: bool, name: &'static str },
Native { f: NativeFn, kind: NativeKind, constructor: bool, name: &'static str, prefix: &'static str },
Pausable { f: crate::interp::PausableFn, name: &'static str },
Host { f: Rc<HostFn>, name: Rc<str> },
Data { f: DataFn, name: Rc<str>, read: crate::host::ArgRead },
@@ -227,6 +238,13 @@ pub(crate) enum Class {
RegExp(Rc<crate::regexp_vm::Regex>),
/// A `Date` object and its time value.
Date(f64),
/// A Symbol object made by ToObject, with its Symbol (ECMA-262 11th edition, section 19.4).
Symbol(crate::symbol::Sym),
/// An Array Iterator or a String Iterator and how far it has gone (sections 22.1.5 and 21.1.5).
Iterator(Box<crate::builtins::iterator::IterState>),
/// The Iterator Record of a `for-of` loop, an array pattern or a spread in progress, on the
/// operand stack only.
IterRecord(Box<crate::iteration::IterRecord>),
ForIn(Box<ForIn>),
/// The `Math` object (section 15.8).
Math,
@@ -314,7 +332,7 @@ impl Class {
Class::XmlFilter(_) => "Object",
Class::Math => "Math",
Class::Json => "JSON",
Class::Ordinary | Class::ForIn(_) => "Object",
Class::Ordinary | Class::ForIn(_) | Class::Symbol(_) | Class::Iterator(_) | Class::IterRecord(_) => "Object",
Class::Array { .. } => "Array",
Class::Function(_) => "Function",
Class::Error(_) => "Error",
@@ -334,11 +352,13 @@ pub(crate) struct Object {
pub(crate) proto: Option<ObjId>,
pub(crate) extensible: bool,
pub(crate) props: PropMap<Prop>,
/// The properties whose keys are Symbols, once the object has one.
pub(crate) syms: Option<Box<crate::symbol::SymProps>>,
}
impl Object {
pub(crate) fn new(class: Class, proto: Option<ObjId>) -> Self {
Self { class, proto, extensible: true, props: PropMap::default() }
Self { class, proto, extensible: true, props: PropMap::default(), syms: None }
}
}
@@ -418,6 +438,8 @@ pub(crate) const XML_LIST_BYTES: usize = 96;
pub(crate) const XML_REF_BYTES: usize = 8;
/// The estimated bytes of a namespace an XML node holds.
pub(crate) const XML_NS_BYTES: usize = 48;
/// The estimated bytes of a Symbol without its description.
pub(crate) const SYMBOL_BYTES: usize = 48;
/// The estimated bytes of the measurement a `UnitValue` object holds.
pub(crate) const UNIT_VALUE_BYTES: usize = 32;
/// The estimated bytes of a piece of code without its instructions, tables and strings.
@@ -493,6 +515,12 @@ impl Heap {
}
}
/// The objects in the heap, in the order of their cells.
pub(crate) fn object_ids(&self) -> Vec<ObjId> {
let ids = self.cells.iter().enumerate().filter(|(_, c)| matches!(c, Cell::Object(_)));
ids.filter_map(|(i, _)| u32::try_from(i).ok().map(ObjId)).collect()
}
/// Live cells, for tests.
#[cfg(test)]
pub(crate) fn live_cells(&self) -> usize {
@@ -582,16 +610,34 @@ impl StringSizes {
self.bytes += string_bytes(k.len());
}
}
/// Adds a Symbol and its description, once however many values and keys share it.
fn add_symbol(&mut self, s: &crate::symbol::Sym) {
if self.seen.insert(s.addr()) {
self.bytes += SYMBOL_BYTES;
if let Some(d) = s.description() {
self.add(d);
}
}
}
}
fn mark_value(v: &Value, work: &mut Vec<u32>, strings: &mut StringSizes) {
match v {
Value::Object(o) => work.push(o.0),
Value::String(s) => strings.add(s),
Value::Symbol(s) => strings.add_symbol(s),
_ => {}
}
}
fn mark_prop(prop: &Prop, work: &mut Vec<u32>, strings: &mut StringSizes) {
match prop {
Prop::Data { value, .. } => mark_value(value, work, strings),
Prop::Accessor { get, set, .. } => work.extend(get.iter().chain(set.iter()).map(|f| f.0)),
}
}
/// The estimated bytes of `code` with the functions nested in it and its source text, for
/// charging code made at run time to the heap before anything refers to it.
pub(crate) fn code_bytes(code: &Code) -> usize {
@@ -620,6 +666,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) {
+ code.names.len()
+ code.functions.len()
+ code.params.len()
+ code.pattern_names.len()
+ code.vars.len()
+ 2 * code.fun_decls.len()
+ code.scopes.iter().map(|s| 2 + s.lets.len() + 2 * s.funcs.len()).sum::<usize>()
@@ -639,7 +686,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) {
strings.add(pattern);
strings.add(flags);
}
let keys = code.names.iter().chain(&code.params).chain(&code.vars).chain(code.fun_decls.iter().map(|(k, _)| k));
let keys = code.names.iter().chain(&code.params).chain(&code.pattern_names).chain(&code.vars).chain(code.fun_decls.iter().map(|(k, _)| k));
for k in keys.chain(&code.self_name).chain(&code.decl_name).chain(&code.rest) {
strings.add_key(k);
}
@@ -659,10 +706,12 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
}
for (k, prop) in o.props.iter() {
strings.add_key(k);
match prop {
Prop::Data { value, .. } => mark_value(value, work, strings),
Prop::Accessor { get, set, .. } => work.extend(get.iter().chain(set.iter()).map(|f| f.0)),
}
mark_prop(prop, work, strings);
}
let syms = o.syms.as_ref().map_or(0, |m| m.len());
for (k, prop) in o.syms.iter().flat_map(|m| m.iter()) {
strings.add_symbol(k);
mark_prop(prop, work, strings);
}
let mut extra = 0;
match &o.class {
@@ -689,6 +738,20 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
work.extend(state.object.iter().map(|o| o.0));
strings.bytes += state.keys.iter().map(|k| string_bytes(k.len())).sum::<usize>();
}
Class::Symbol(s) => strings.add_symbol(s),
Class::IterRecord(r) => {
mark_value(&r.iterator, work, strings);
mark_value(&r.next, work, strings);
match &r.walk {
Some(crate::iteration::Walk::Array(a, _)) => work.push(a.0),
Some(crate::iteration::Walk::String(s, _)) => strings.add(s),
None => {}
}
}
Class::Iterator(state) => match &**state {
crate::builtins::iterator::IterState::Array { target, .. } => work.extend(target.iter().map(|o| o.0)),
crate::builtins::iterator::IterState::String { text, .. } => text.iter().for_each(|s| strings.add(s)),
},
Class::Xml(node) => {
work.extend(node.parent.iter().chain(&node.attrs).chain(&node.children).map(|o| o.0));
strings.add(&node.value);
@@ -716,7 +779,7 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
Class::UnitValue(_) => extra = UNIT_VALUE_BYTES,
_ => {}
}
OBJECT_BYTES + PROP_BYTES * o.props.len() + extra
OBJECT_BYTES + PROP_BYTES * (o.props.len() + syms) + extra
}
fn add_name(name: &XmlName, strings: &mut StringSizes) {
+18 -2
View File
@@ -245,6 +245,7 @@ impl Interp {
Ok(Data::String(s.to_rust_string()))
}
Value::Object(id) => self.read_object(*id, r),
Value::Symbol(_) => Err(self.data_error(r, ErrorType::Type, "is a Symbol, not plain data")),
}
}
@@ -270,6 +271,14 @@ impl Interp {
return Err(self.data_error(r, ErrorType::Type, &what));
}
};
// Each Symbol key the scan may visit takes a unit of fuel first.
let syms = self.object(id)?.syms.as_ref().map_or(0, |m| m.len());
if syms > 0 {
crate::regexp_vm::use_fuel_n(self, syms as u64)?;
}
if self.object(id)?.syms.as_ref().is_some_and(|m| m.iter().any(|(_, p)| p.enumerable())) {
return Err(self.data_error(r, ErrorType::Type, "has a Symbol-keyed property, not plain data"));
}
r.ancestors.push(id);
let out = match shape {
Shape::Array(length) => self.read_array(id, length, r),
@@ -530,7 +539,14 @@ impl Interp {
/// `v` as the string `String(v)` gives, within the limits of a crossing.
fn read_text(&mut self, v: &Value, r: &mut Reading) -> JsResult<Data> {
let s = self.to_str(v)?;
let s = match v {
// `String(symbol)` gives `Symbol(description)` (ECMA-262 11th edition, section 21.1.1.1).
Value::Symbol(k) => match self.descriptive_string(k)? {
Value::String(s) => s,
_ => return Err(Abrupt::Internal("a Symbol's descriptive string is not a string".into())),
},
_ => self.to_str(v)?,
};
self.charge_reading(r, s.len().saturating_mul(3).saturating_add(2))?;
Ok(Data::String(s.to_rust_string()))
}
@@ -597,7 +613,7 @@ impl Interp {
HostItem::Script(item) => match crate::builtins::extensions::getter(item) {
None => Prop::Data { value: Value::Object(self.global), flags: ENUMERABLE },
Some((name, f)) => {
let get = crate::builtins::native(self, name, f, 0, crate::heap::NativeKind::Plain, false)?;
let get = crate::builtins::accessor_native(self, "get ", name, f, 0)?;
Prop::Accessor { get: Some(get), set: None, flags: ENUMERABLE }
}
},
+39
View File
@@ -325,6 +325,45 @@ fn a_text_function_takes_each_argument_as_string_gives_it() {
assert!(e.message.contains("no text"), "{}", e.message);
}
#[test]
fn a_symbol_crosses_as_the_text_string_gives_it_and_never_as_data() {
let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 10_000_000, ..Limits::default() });
let seen = with_take(&mut r);
let texts: Rc<RefCell<Vec<Data>>> = Rc::default();
let log = texts.clone();
let f: HostFunction = Rc::new(move |args| {
log.borrow_mut().extend(args);
Ok(Data::Undefined)
});
r.define_host_object("text", vec![("of".into(), HostItem::TextFunction(f))]).unwrap();
r.run("text.of(Symbol('tag'), Symbol())").unwrap();
assert_eq!(texts.borrow().as_slice(), [Data::String("Symbol(tag)".into()), Data::String("Symbol()".into())]);
// An enumerable Symbol-keyed property is refused; one that is not enumerable is left out.
let probe = "var e = 'none'; var v = {a: 1}; v[Symbol('k')] = 2; try { host.take(v); } catch (x) { e = x.name + '|' + x.message; } e";
let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") };
assert!(out.starts_with("TypeError|") && out.contains("has a Symbol-keyed property"), "{out}");
let probe = "var e = 'none'; var v = [1]; v[Symbol('k')] = 2; try { host.take({list: v}); } catch (x) { e = x.name + '|' + x.message; } e";
let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") };
assert!(out.starts_with("TypeError|") && out.contains(".list has a Symbol-keyed property"), "{out}");
assert!(seen.borrow().is_empty(), "the function ran");
r.run("var v = {a: 1}; Object.defineProperty(v, Symbol('k'), {value: 2}); host.take(v);").unwrap();
assert_eq!(seen.borrow().as_slice(), [Data::Object(vec![("a".into(), Data::Number(1.0))])]);
}
#[test]
fn checking_the_symbol_keys_of_a_value_takes_fuel() {
// Making the 20,000 hidden keys takes well under 3,000,000 units, in a run of its own; the 500
// crossings check 10,000,000 keys.
let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 3_000_000, ..Limits::default() });
with_take(&mut r);
let setup = "var v = {}; for (var i = 0; i < 20000; i++) Object.defineProperty(v, Symbol(), {value: i}); true";
assert_eq!(r.run(setup), Ok(JsValue::Bool(true)));
match r.run("for (var j = 0; j < 500; j++) host.take(v);") {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {}
other => panic!("{other:?}"),
}
}
#[test]
fn errors_from_the_host_can_be_caught_and_an_abort_cannot() {
let mut r = realm(1_000_000);
+349 -241
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -991,6 +991,10 @@ fn code(ops: Vec<Op>) -> Code {
arrow: false,
uses_this: false,
param_init: false,
pattern_names: Vec::new(),
es2015: false,
own_name: None,
method: false,
}
}
+299
View File
@@ -0,0 +1,299 @@
//! The iterator protocol as `for-of`, array destructuring and spread use it (ECMA-262 11th
//! edition, <https://262.ecma-international.org/11.0/>): GetIterator (section 7.4.1),
//! IteratorStep (section 7.4.5) and IteratorClose (section 7.4.6), and the instructions that run
//! them.
//!
//! An Iterator Record lives on the operand stack as an object of its own class, which no script
//! can reach. Its `done` flag is set before each call that can throw, so a handler that closes
//! the iterator on an exception does not call `return` for an iterator that threw itself, has
//! finished, or is being closed already. Each step takes a unit of fuel.
//!
//! A realm made without [`crate::Options::es2015`] has no `Symbol.iterator`. When such a realm
//! later reads ECMAScript 2015 code ([`crate::Realm::set_es2015`]), arrays, `arguments` objects
//! and strings are walked as their iterators would walk them, and other values are not iterable.
use crate::heap::{Class, OPEN, ObjId, Object, PROP_BYTES, Prop, key, string_bytes};
use crate::interp::{Abrupt, ErrorType, Interp, JsResult, internal};
use crate::value::{Str, Value, index_key, number_to_str};
/// An Iterator Record (section 7.4.1): the iterator, its `next` method, and whether it is done.
#[derive(Clone)]
pub(crate) struct IterRecord {
pub(crate) iterator: Value,
pub(crate) next: Value,
pub(crate) done: bool,
/// In a realm without the ECMAScript 2015 built-ins (one made without
/// [`crate::Options::es2015`] that later reads ECMAScript 2015 code), the walk over an array,
/// an `arguments` object or a string that stands in for their iterators.
pub(crate) walk: Option<Walk>,
}
/// A walk that steps as `%ArrayIteratorPrototype%.next` and `%StringIteratorPrototype%.next` do.
#[derive(Clone)]
pub(crate) enum Walk {
/// The object, read with its `length` at each step, and the next index.
Array(ObjId, f64),
/// The string, flat, and the next position in code units.
String(Str, usize),
}
impl Interp {
fn record(&mut self, rec: ObjId) -> JsResult<&mut IterRecord> {
match &mut self.object_mut(rec)?.class {
Class::IterRecord(r) => Ok(r),
_ => internal("not an iterator record"),
}
}
fn record_at(&self, n: usize) -> JsResult<ObjId> {
match self.peek(n)? {
Value::Object(o) => Ok(o),
_ => internal("iterator record is not an object"),
}
}
/// GetIterator (section 7.4.1): the record of the iterator `v`'s `@@iterator` method gives.
pub(crate) fn get_iterator(&mut self, v: &Value) -> JsResult<ObjId> {
let method = match self.well_known(|w| &w.iterator) {
Some(sym) if !v.is_nullish() => self.get_value_sym(v, &sym)?,
Some(_) => Value::Undefined,
None => return self.walk_record(v),
};
if !self.is_callable(&method) {
let what = match v {
Value::Undefined => "undefined",
Value::Null => "null",
_ => "the value",
};
return Err(self.type_error(&format!("{what} is not iterable")));
}
let iterator = self.call(&method, v, &[])?;
if !matches!(iterator, Value::Object(_)) {
return Err(self.type_error("the iterator is not an object"));
}
let next = self.rooted(std::slice::from_ref(&iterator), |i| i.get_value(&iterator, &key("next")))?;
let record = IterRecord { iterator, next, done: false, walk: None };
Ok(self.heap.alloc_object(Object::new(Class::IterRecord(Box::new(record)), None)))
}
/// The record of a [`Walk`] over an array, an `arguments` object, a string or a `String`
/// object, for a realm without `Symbol.iterator`; any other value is not iterable there. A
/// `String` object is converted to a string first, as the string iterator does. A
/// concatenated string's flattened copy is counted against the heap before it is made.
fn walk_record(&mut self, v: &Value) -> JsResult<ObjId> {
let walk = match v {
Value::String(s) => Walk::String(Str::from_rc(crate::string_builtins::flat_charged(self, s)?), 0),
Value::Object(o) if matches!(self.object(*o)?.class, Class::Array { .. } | Class::Arguments(_)) => Walk::Array(*o, 0.0),
Value::Object(o) if matches!(self.object(*o)?.class, Class::String(_)) => {
let s = self.to_str(v)?;
Walk::String(Str::from_rc(crate::string_builtins::flat_charged(self, &s)?), 0)
}
_ => return Err(self.type_error("the value is not iterable")),
};
let record = IterRecord { iterator: Value::Undefined, next: Value::Undefined, done: false, walk: Some(walk) };
Ok(self.heap.alloc_object(Object::new(Class::IterRecord(Box::new(record)), None)))
}
/// One step of the [`Walk`] of `rec`, which is not done: the next value, or `None` at the end.
fn walk_step(&mut self, rec: ObjId, walk: Walk) -> JsResult<Option<Value>> {
self.use_fuel()?;
let (value, walk) = match walk {
Walk::Array(a, i) => {
let length = self.get_from(a, &key("length"), &Value::Object(a))?;
let n = self.to_number(&length)?;
if n.is_nan() || i >= n.trunc() {
return Ok(None);
}
let v = self.get_from(a, &number_to_str(i).flat(), &Value::Object(a))?;
(v, Walk::Array(a, i + 1.0))
}
Walk::String(s, pos) => {
let units = s.flat();
let Some(&first) = units.get(pos) else { return Ok(None) };
let pair = (0xD800..0xDC00).contains(&first) && units.get(pos + 1).is_some_and(|u| (0xDC00..0xE000).contains(u));
let width = if pair { 2 } else { 1 };
let piece = units.get(pos..pos + width).map(<[u16]>::to_vec).unwrap_or_default();
(Value::String(Str::from_units(piece)), Walk::String(s, pos + width))
}
};
let r = self.record(rec)?;
r.walk = Some(walk);
r.done = false;
Ok(Some(value))
}
/// IteratorStep and IteratorValue (sections 7.4.5 and 7.4.4): the next value, or `None` when
/// the iterator is done. The record stays done when the step throws.
pub(crate) fn iter_next(&mut self, rec: ObjId) -> JsResult<Option<Value>> {
self.iter_step(rec, true)
}
/// IteratorStep (section 7.4.5), and IteratorValue when `read_value` is set: the next value
/// (`undefined` when it is not read), or `None` when the iterator is done.
fn iter_step(&mut self, rec: ObjId, read_value: bool) -> JsResult<Option<Value>> {
let r = self.record(rec)?;
if r.done {
return Ok(None);
}
r.done = true;
if let Some(walk) = r.walk.clone() {
return self.walk_step(rec, walk);
}
let (iterator, next) = (r.iterator.clone(), r.next.clone());
self.use_fuel()?;
let result = self.call(&next, &iterator, &[])?;
if !matches!(result, Value::Object(_)) {
return Err(self.type_error("the iterator result is not an object"));
}
let value = self.rooted(std::slice::from_ref(&result), |i| {
if i.get_value(&result, &key("done"))?.truthy() {
return Ok(None);
}
if !read_value {
return Ok(Some(Value::Undefined));
}
i.get_value(&result, &key("value")).map(Some)
})?;
if value.is_some() {
self.record(rec)?.done = false;
}
Ok(value)
}
/// IteratorClose (section 7.4.6) with a normal completion: calls the iterator's `return`
/// method, unless it is done, and checks that it gives an object.
fn iter_close(&mut self, rec: ObjId) -> JsResult<()> {
let r = self.record(rec)?;
if r.done {
return Ok(());
}
r.done = true;
if r.walk.is_some() {
return Ok(());
}
let iterator = r.iterator.clone();
self.rooted(std::slice::from_ref(&iterator), |i| {
let method = i.get_value(&iterator, &key("return"))?;
if method.is_nullish() {
return Ok(());
}
if !i.is_callable(&method) {
return Err(i.type_error("the iterator's return is not a function"));
}
match i.call(&method, &iterator, &[])? {
Value::Object(_) => Ok(()),
_ => Err(i.type_error("the iterator's return gave something that is not an object")),
}
})
}
/// `value` → `record`.
pub(crate) fn op_get_iterator(&mut self) -> JsResult<()> {
let v = self.peek(0)?;
let rec = self.get_iterator(&v)?;
self.replace(1, Value::Object(rec))
}
/// `record` → `record value`, or jumps with `record` when the iterator is done.
pub(crate) fn op_iter_step(&mut self, target: u32) -> JsResult<()> {
let rec = self.record_at(0)?;
match self.iter_next(rec)? {
Some(v) => self.push(v),
None => self.jump_to(target),
}
}
/// `record x₁…xₙ` → `record x₁…xₙ value`: the next value, or `undefined` when the iterator
/// is done.
pub(crate) fn op_iter_value(&mut self, under: u32) -> JsResult<()> {
let rec = self.record_at(under as usize)?;
let v = self.iter_next(rec)?.unwrap_or(Value::Undefined);
self.push(v)
}
/// `record` → `record`: one step of the iterator, for a hole in an array pattern
/// (section 13.3.3.6, Elision), which does not read the result's `value`.
pub(crate) fn op_iter_skip(&mut self) -> JsResult<()> {
let rec = self.record_at(0)?;
self.iter_step(rec, false).map(drop)
}
/// `record x₁…xₙ` → `record x₁…xₙ array`: an array of the values left.
pub(crate) fn op_iter_rest(&mut self, under: u32) -> JsResult<()> {
let rec = self.record_at(under as usize)?;
let proto = self.intrinsics.array_proto;
let a = self.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: true }, Some(proto)));
self.push(Value::Object(a))?;
self.append_values(rec, a)
}
/// Appends the values the iterator of `rec` gives to the array `a`; both are on the stack.
fn append_values(&mut self, rec: ObjId, a: ObjId) -> JsResult<()> {
while let Some(v) = self.iter_next(rec)? {
let Class::Array { length, .. } = &self.object(a)?.class else { return internal("not an array") };
let i = *length;
if i == u32::MAX - 1 {
return Err(self.throw(ErrorType::Range, "array too long"));
}
let k = index_key(i);
self.rooted(std::slice::from_ref(&v), |interp| interp.reserve_heap(PROP_BYTES + string_bytes(k.len())))?;
let Class::Array { length, .. } = &mut self.object_mut(a)?.class else { return internal("not an array") };
*length = i + 1;
self.define(a, k, Prop::Data { value: v, flags: OPEN })?;
}
Ok(())
}
/// `array value` → `array`, with the values the value's iterator gives appended (spread,
/// ECMA-262 11th edition section 12.2.5.2).
pub(crate) fn op_array_spread(&mut self) -> JsResult<()> {
let v = self.peek(0)?;
let Value::Object(a) = self.peek(1)? else { return internal("spread into something that is not an array") };
let rec = self.get_iterator(&v)?;
self.replace(1, Value::Object(rec))?;
self.append_values(rec, a)?;
self.pop().map(drop)
}
/// `record` → nothing: closes the iterator unless it is done.
pub(crate) fn op_iter_close(&mut self) -> JsResult<()> {
let rec = self.record_at(0)?;
self.iter_close(rec)?;
self.pop().map(drop)
}
/// `record exception` → throws the exception, after closing the iterator unless it is done.
/// What closing it throws is dropped, the lookup of `return` included (ECMA-262 2023 section
/// 7.4.8, steps 4 to 6); running out of fuel, heap or time is not. The exception stays in its
/// stack slot while the iterator is closed, so [`Interp::rethrow`] finds the source position
/// and host mark kept for that slot.
pub(crate) fn op_iter_close_throw(&mut self) -> JsResult<()> {
let rec = self.record_at(1)?;
match self.iter_close(rec) {
Ok(()) | Err(Abrupt::Throw(_)) => {
let exception = self.pop()?;
Err(self.rethrow(exception))
}
Err(other) => Err(other),
}
}
/// `value` → `value`: a `TypeError` when it is `undefined` or `null` (RequireObjectCoercible,
/// section 7.2.1), before an object pattern reads it.
pub(crate) fn op_require_object_coercible(&mut self) -> JsResult<()> {
let v = self.peek(0)?;
if v.is_nullish() {
let what = if matches!(v, Value::Null) { "null" } else { "undefined" };
return Err(self.type_error(&format!("cannot destructure {what}")));
}
Ok(())
}
/// `object key x₁…xₙ` → `object key x₁…xₙ object[key]`.
pub(crate) fn op_pattern_get(&mut self, under: u32) -> JsResult<()> {
let k = self.peek(under as usize)?;
let object = self.peek(under as usize + 1)?;
let v = self.with_prop_key(&k, |i, pk| i.get_value_pk(&object, &pk))?;
self.push(v)
}
}
+43 -8
View File
@@ -53,10 +53,31 @@
//! loop, function declarations in blocks scoped to the block (Annex B.3.3 in sloppy code), arrow
//! functions (section 14.2), template literals and tagged templates (sections 12.2.9 and
//! 12.3.7), default and rest parameters (section 14.1) and spread in array literals, calls and
//! `new` (sections 12.2.5 and 12.3.6.1). Spread reads arrays by index, reading the length again
//! before each element, strings and `String` objects by code point, and objects with a `length` by
//! index; other values are a `TypeError`. Destructuring, `for … of`, classes,
//! generators and modules stay syntax errors.
//! `new` (sections 12.2.5 and 12.3.6.1), `for … of` loops (section 13.7.5), array and object
//! destructuring in declarations, assignments, parameters and `catch` clauses (sections 12.15.5
//! and 13.3.3), shorthand and computed property names, methods and `__proto__: value` in object
//! literals (sections 12.2.6, 14.3 and B.3.1), and the `name` property of functions (section
//! 9.2.11).
//! Spread, `for … of` and array patterns use the iterator protocol of the 11th edition
//! (<https://262.ecma-international.org/11.0/>, section 7.4), and a loop or pattern left early
//! closes its iterator. In a realm made without the option and later given it with
//! [`Realm::set_es2015`], which has no `Symbol.iterator`, they walk arrays and `arguments` objects
//! by index and strings by code point, and throw a `TypeError` for other values.
//! Object rest properties (`{ a, ...rest }`), classes, generators and modules stay syntax errors.
//!
//! With [`Options::es2015`], the realm also has `Symbol` (ECMA-262 11th edition, section 19.4,
//! <https://262.ecma-international.org/11.0/>): `Symbol.for` and `Symbol.keyFor` over a registry
//! that lasts as long as the realm, the well-known Symbols `iterator`, `asyncIterator`,
//! `hasInstance`, `toPrimitive` and `toStringTag` with the hooks ToPrimitive, `instanceof` and
//! `Object.prototype.toString` read, Symbol-keyed properties with `Object.getOwnPropertySymbols`,
//! and iterator objects with a `next` method from `Array.prototype.values`, `keys`, `entries` and
//! `@@iterator`, `String.prototype[@@iterator]` (by code point) and every `arguments` object.
//! `Date.prototype[@@toPrimitive]` converts a Date without a hint as with the String hint, and an
//! object without an `@@toPrimitive` method, a Date included, converts without a hint as with the
//! Number hint. A Symbol converted to a string or a number without `String(symbol)` or `toString` throws a
//! `TypeError`. A string converts to a number in the `0b` and `0o` forms as well. Every iterator
//! step and every prototype a Symbol-keyed lookup passes takes fuel, and every Symbol and registry
//! entry counts against the heap limit.
#![forbid(unsafe_code)]
pub mod ast;
@@ -70,6 +91,7 @@ mod file_classes;
mod heap;
mod host;
mod interp;
mod iteration;
mod lexer;
mod number;
mod number_builtins;
@@ -79,6 +101,7 @@ mod regexp;
mod regexp_builtins;
mod regexp_vm;
mod string_builtins;
mod symbol;
mod token;
mod unit_value;
mod value;
@@ -87,8 +110,9 @@ mod xml_builtins;
mod xpath;
pub use ast::{
AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind, LexKind, LogicalOp, Name, Program,
Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
AssignOp, Ast, BinaryOp, Binding, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind, LexKind, LogicalOp, Name,
Program, Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart,
XmlQualifier,
};
pub use builtins::extensions::Localization;
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
@@ -113,10 +137,17 @@ pub struct Options {
/// Read and run E4X (ECMA-357). Off, XML syntax is an error and a realm has no XML built-ins.
pub e4x: bool,
/// Read and run the ECMAScript 2015 forms this engine has: `let` and `const`, arrow functions,
/// template literals (tagged ones included), default and rest parameters, and spread in array
/// literals, calls and `new`, and from ECMAScript 2020 optional chains (`a?.b`, `a?.[k]`,
/// template literals (tagged ones included), default and rest parameters, spread in array
/// literals, calls and `new`, `for … of`, array and object destructuring, and shorthand and
/// computed property names, and from ECMAScript 2020 optional chains (`a?.b`, `a?.[k]`,
/// `f?.()`) and `??`. Off, they are syntax errors and the language is ES5.1's. Code a
/// script evaluates at run time (`eval`, `Function`) is read the way the realm reads scripts.
/// A realm made with it on also has the later editions' built-ins this engine has: `Symbol`
/// with Symbol-keyed properties and the iterators of arrays, strings and `arguments` objects.
/// A realm made with it off has the ES5.1 built-ins only, as the app's scripts expect. Those
/// built-ins are chosen when the realm is made: turning the option on or off later with
/// [`Realm::set_es2015`] changes the language later runs read, and does not add or remove
/// them. Runs with it on also convert `0b` and `0o` strings to numbers.
pub es2015: bool,
}
@@ -221,6 +252,8 @@ impl LineTable {
#[cfg(test)]
mod builtins_tests;
#[cfg(test)]
mod es2015_object_tests;
#[cfg(test)]
mod es2015_tests;
#[cfg(test)]
mod es2020_tests;
@@ -231,6 +264,8 @@ mod host_tests;
#[cfg(test)]
mod interp_tests;
#[cfg(test)]
mod symbol_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod text_tests;
+194 -76
View File
@@ -7,14 +7,15 @@
//! stack, and prefix operators, assignment chains, `else if` chains and labels with loops, so long
//! runs of them do not nest at all.
mod pattern;
mod xml;
use std::collections::{HashMap, HashSet};
use crate::LineTable;
use crate::ast::{
AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionKind, LexKind, LogicalOp, Name, Program, Property,
PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl,
AssignOp, Ast, BinaryOp, Binding, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionKind, LexKind, LogicalOp, Name, Program,
Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl,
};
use crate::error::{SyntaxError, TOO_DEEP};
use crate::lexer::{Goal, Lexer};
@@ -56,9 +57,9 @@ struct Scope {
function: bool,
}
/// The parameters of a function as they are read: plain names, each name's default value, and a
/// rest parameter.
type Params = (Vec<Name>, Vec<Option<ExprId>>, Option<Name>);
/// The parameters of a function as they are read: names or patterns, each one's default value,
/// and a rest parameter.
type Params = (Vec<Binding>, Vec<Option<ExprId>>, Option<Binding>);
/// A binary operator, with the logical ones apart.
#[derive(Clone, Copy, Debug)]
@@ -101,6 +102,19 @@ pub(crate) struct Parser<'s> {
es2015: bool,
/// The scopes open around the current token, outermost first (only with `es2015`).
scopes: Vec<Scope>,
/// Where each shorthand property with an initializer (`{a = 1}`) not yet read as part of a
/// destructuring pattern starts; one left when its expression ends is a `SyntaxError`.
cover_inits: Vec<u32>,
/// The next assignment expression may leave such properties to a pattern around it: it is an
/// element of an array or object literal, an arrow function's parenthesized head or a
/// `for` loop's head.
cover_ok: bool,
/// The spread elements of array literals followed by a comma, which cannot end a pattern.
rest_commas: HashSet<u32>,
/// Where each `__proto__: value` after the first in an object literal starts (ECMA-262 2015
/// section B.3.1). Each is also in `cover_inits`, so it is a `SyntaxError` unless the literal
/// is read as a destructuring pattern.
proto_twice: HashSet<u32>,
}
impl<'s> Parser<'s> {
@@ -125,6 +139,10 @@ impl<'s> Parser<'s> {
e4x: options.e4x,
es2015: options.es2015,
scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() },
cover_inits: Vec::new(),
cover_ok: false,
rest_commas: HashSet::new(),
proto_twice: HashSet::new(),
};
parser.tok = parser.next_significant()?;
Ok(parser)
@@ -375,25 +393,32 @@ impl<'s> Parser<'s> {
}
/// `let` or `const` declarations after the keyword: each name declared in the innermost scope.
/// `no_in` leaves `in` to a `for (… in …)` around them, where a `const` may go without an
/// initializer.
/// `no_in` leaves `in` to a `for (… in …)` around them, where a `const` or a pattern may go
/// without an initializer, as in `for (… of …)`.
fn parse_lexical_decls(&mut self, kind: LexKind, no_in: bool) -> Result<Vec<VarDecl>> {
let mut decls = Vec::new();
loop {
if self.at(Punct::LBracket) || self.at(Punct::LBrace) {
return Err(self.error_at_token(&self.tok, "destructuring declarations are not supported"));
let target = self.parse_declaration_target()?;
for name in self.ast.bound_names(&target) {
if name.name == "let" {
return Err(self.error_at_offset(name.span.start, "'let' cannot be the name of a let or const declaration"));
}
self.declare_lexical(&name, false)?;
}
let name = self.binding_identifier()?;
if name.name == "let" {
return Err(self.error_at_offset(name.span.start, "'let' cannot be the name of a let or const declaration"));
}
self.declare_lexical(&name, false)?;
let init = if self.eat(Punct::Eq)? { Some(self.parse_assignment(no_in)?) } else { None };
let in_head = no_in && self.at_keyword(Keyword::In) && decls.is_empty();
if kind == LexKind::Const && init.is_none() && !in_head {
return Err(self.error_at_offset(name.span.start, format!("const '{}' needs an initializer", name.name)));
let in_head = no_in && (self.at_keyword(Keyword::In) || self.at_of()) && decls.is_empty();
if init.is_none() && !in_head {
match &target {
Binding::Pattern(p) => {
return Err(self.error_at_offset(self.ast.expr_span(*p).start, "a destructuring declaration needs an initializer"));
}
Binding::Name(name) if kind == LexKind::Const => {
return Err(self.error_at_offset(name.span.start, format!("const '{}' needs an initializer", name.name)));
}
Binding::Name(_) => {}
}
}
decls.push(VarDecl { name, init });
decls.push(VarDecl { target, init });
if !self.eat(Punct::Comma)? {
return Ok(decls);
}
@@ -525,6 +550,11 @@ impl<'s> Parser<'s> {
Ok(self.ast.push_stmt(Stmt::Empty, start))
}
TokenKind::Keyword(k) => self.keyword_statement(*k, start),
// An expression statement cannot start with `let [` (ECMA-262 2015 section 13.5); in
// a statement list that starts a declaration, and elsewhere it is an error.
_ if self.es2015 && self.tok.ident() == Some("let") && !self.tok.escaped && self.peek().is_some_and(|t| t.is_punct(Punct::LBracket)) => {
Err(self.error_at_token(&self.tok, "a lexical declaration cannot stand here; put it in a block"))
}
_ => {
let expr = self.parse_expression(false)?;
self.semicolon()?;
@@ -571,10 +601,20 @@ impl<'s> Parser<'s> {
}
/// `{ … }`, a scope of its own; `param` is a catch clause's parameter, which a lexical
/// declaration in the block must not take.
fn parse_block_with(&mut self, param: Option<&str>) -> Result<Vec<StmtId>> {
/// declaration in the block must not take. A pattern's names are not taken by a `var` in the
/// block either (ECMA-262 2015 section 13.15.1 and Annex B.3.5).
fn parse_block_with(&mut self, param: Option<&Binding>) -> Result<Vec<StmtId>> {
self.expect(Punct::LBrace)?;
self.push_scope(false, param.map(str::to_string));
match param {
Some(Binding::Name(name)) => self.push_scope(false, std::iter::once(name.name.clone())),
Some(Binding::Pattern(p)) => {
self.push_scope(false, std::iter::empty());
for name in self.ast.pattern_names(*p) {
self.declare_lexical(&name, false)?;
}
}
None => self.push_scope(false, std::iter::empty()),
}
let body = self.block_items();
self.pop_scope();
let body = body?;
@@ -597,10 +637,18 @@ impl<'s> Parser<'s> {
fn parse_var_decls(&mut self, no_in: bool) -> Result<Vec<VarDecl>> {
let mut decls = Vec::new();
loop {
let name = self.binding_identifier()?;
self.declare_var(&name)?;
let target = self.parse_declaration_target()?;
for name in self.ast.bound_names(&target) {
self.declare_var(&name)?;
}
let init = if self.eat(Punct::Eq)? { Some(self.parse_assignment(no_in)?) } else { None };
decls.push(VarDecl { name, init });
if let (Binding::Pattern(p), None) = (&target, init) {
let in_head = no_in && (self.at_keyword(Keyword::In) || self.at_of()) && decls.is_empty();
if !in_head {
return Err(self.error_at_offset(self.ast.expr_span(*p).start, "a destructuring declaration needs an initializer"));
}
}
decls.push(VarDecl { target, init });
if !self.eat(Punct::Comma)? {
return Ok(decls);
}
@@ -689,22 +737,46 @@ impl<'s> Parser<'s> {
} else if self.at_keyword(Keyword::Var) {
self.bump()?;
let mut decls = self.parse_var_decls(true)?;
if decls.len() == 1 && self.at_of() {
let decl = decls.pop().ok_or_else(|| self.unexpected())?;
return self.parse_for_of_var(decl, start);
}
if decls.len() == 1 && self.at_keyword(Keyword::In) {
let decl = decls.pop().ok_or_else(|| self.unexpected())?;
// The variable of a for-in loop takes an initializer only outside strict mode
// code (ECMA-262 2017 Annex B.3.6).
if self.ctx.strict && decl.init.is_some() {
return Err(self.error_at_token(&self.tok, "a for-in variable cannot have an initializer in strict mode code"));
// code, and only when it is a name (ECMA-262 2017 Annex B.3.6).
if decl.init.is_some() && (self.ctx.strict || matches!(decl.target, Binding::Pattern(_))) {
return Err(self.error_at_token(&self.tok, "a for-in variable cannot have an initializer here"));
}
return self.parse_for_in(ForInTarget::Var(decl), start, false);
}
Some(ForInit::Var(decls))
} else {
let starts_with_let = self.tok.ident() == Some("let") && !self.tok.escaped;
let async_of =
self.tok.ident() == Some("async") && !self.tok.escaped && self.peek().is_some_and(|t| t.ident() == Some("of") && !t.escaped);
let mark = self.cover_inits.len();
self.cover_ok = self.es2015;
let expr = self.parse_expression(true)?;
if self.at_of() {
if starts_with_let {
return Err(self.error_at_offset(self.ast.expr_span(expr).start, "a for-of loop's left-hand side cannot start with 'let'"));
}
// `for (async of …` is a SyntaxError, as ECMAScript 2021 has it (ECMA-262 12th
// edition section 14.7.5, the lookahead restriction on `async of`).
if async_of {
return Err(self.error_at_offset(self.ast.expr_span(expr).start, "a for-of loop's left-hand side cannot be 'async'"));
}
self.loop_target(expr, "invalid left-hand side in for-of loop", true)?;
self.check_cover(mark)?;
return self.parse_for_of(ForInTarget::Expr(expr), start);
}
if self.at_keyword(Keyword::In) {
self.check_target(expr, "invalid left-hand side in for-in loop")?;
self.loop_target(expr, "invalid left-hand side in for-in loop", false)?;
self.check_cover(mark)?;
return self.parse_for_in(ForInTarget::Expr(expr), start, false);
}
self.check_cover(mark)?;
Some(ForInit::Expr(expr))
};
self.parse_for_rest(init, start)
@@ -724,12 +796,15 @@ impl<'s> Parser<'s> {
/// `for (let …` or `for (const …`, after the keyword, in the loop's own scope.
fn parse_for_lexical(&mut self, kind: LexKind, start: Span) -> Result<StmtId> {
let mut decls = self.parse_lexical_decls(kind, true)?;
if decls.len() == 1 && self.at_keyword(Keyword::In) {
if decls.len() == 1 && (self.at_keyword(Keyword::In) || self.at_of()) {
let Some(decl) = decls.pop() else { return Err(self.unexpected()) };
if decl.init.is_some() {
return Err(self.error_at_token(&self.tok, "a for-in variable declared with let or const cannot have an initializer"));
return Err(self.error_at_token(&self.tok, "a loop variable declared with let or const cannot have an initializer here"));
}
return self.parse_for_in(ForInTarget::Lexical(kind, decl.name), start, false);
if self.at_of() {
return self.parse_for_of(ForInTarget::Lexical(kind, decl.target), start);
}
return self.parse_for_in(ForInTarget::Lexical(kind, decl.target), start, false);
}
self.parse_for_rest(Some(ForInit::Lexical(kind, decls)), start)
}
@@ -760,8 +835,11 @@ impl<'s> Parser<'s> {
self.pop_scope();
return result;
}
let mark = self.cover_inits.len();
self.cover_ok = self.es2015;
let expr = self.parse_expression(true)?;
self.check_target(expr, "invalid left-hand side in for each loop")?;
self.loop_target(expr, "invalid left-hand side in for each loop", false)?;
self.check_cover(mark)?;
self.parse_for_in(ForInTarget::Expr(expr), start, true)
}
@@ -773,9 +851,9 @@ impl<'s> Parser<'s> {
return Err(self.error_at_token(&self.tok, "for each takes one variable"));
};
if decl.init.is_some() {
return Err(self.error_at_token(&self.tok, "a for-in variable declared with let or const cannot have an initializer"));
return Err(self.error_at_token(&self.tok, "a loop variable declared with let or const cannot have an initializer here"));
}
self.parse_for_in(ForInTarget::Lexical(kind, decl.name), start, true)
self.parse_for_in(ForInTarget::Lexical(kind, decl.target), start, true)
}
/// `break` or `continue`, with an optional label on the same line, which must name a label
@@ -900,12 +978,9 @@ impl<'s> Parser<'s> {
let handler = if self.at_keyword(Keyword::Catch) {
self.bump()?;
self.expect(Punct::LParen)?;
if self.es2015 && (self.at(Punct::LBracket) || self.at(Punct::LBrace)) {
return Err(self.error_at_token(&self.tok, "destructuring catch parameters are not supported"));
}
let param = self.binding_identifier()?;
let param = self.parse_declaration_target()?;
self.expect(Punct::RParen)?;
let body = self.parse_block_with(Some(&param.name))?;
let body = self.parse_block_with(Some(&param))?;
Some(CatchClause { param, body })
} else {
None
@@ -991,20 +1066,20 @@ impl<'s> Parser<'s> {
fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result<crate::ast::FunctionId> {
self.expect(Punct::LParen)?;
let mut params: Vec<Name> = Vec::new();
let mut params: Vec<Binding> = Vec::new();
let mut defaults: Vec<Option<ExprId>> = Vec::new();
let mut rest = None;
if !self.at(Punct::RParen) {
loop {
if self.es2015 && self.at(Punct::Ellipsis) {
self.bump()?;
rest = Some(self.function_name_or_param()?.0);
rest = Some(self.parse_param_target()?);
if !self.at(Punct::RParen) {
return Err(self.error_at_token(&self.tok, "a rest parameter must be the last parameter"));
}
break;
}
let (param, _) = self.function_name_or_param()?;
let param = self.parse_param_target()?;
let default = if self.es2015 && self.eat(Punct::Eq)? { Some(self.parse_assignment(false)?) } else { None };
params.push(param);
defaults.push(default);
@@ -1035,7 +1110,7 @@ impl<'s> Parser<'s> {
defaults.clear();
}
self.expect(Punct::LBrace)?;
let names: Vec<String> = params.iter().chain(&rest).map(|p| p.name.clone()).collect();
let names: Vec<String> = params.iter().chain(&rest).flat_map(|p| self.ast.bound_names(p)).map(|n| n.name).collect();
let outer_strict = self.ctx.strict;
let inner = Context { strict: outer_strict, in_function: true, ..Context::default() };
let outer = std::mem::replace(&mut self.ctx, inner);
@@ -1058,7 +1133,7 @@ impl<'s> Parser<'s> {
}
self.expect(Punct::Arrow)?;
self.enter()?;
let names: Vec<String> = params.iter().chain(&rest).map(|p| p.name.clone()).collect();
let names: Vec<String> = params.iter().chain(&rest).flat_map(|p| self.ast.bound_names(p)).map(|n| n.name).collect();
let outer_strict = self.ctx.strict;
let inner = Context { strict: outer_strict, in_function: true, ..Context::default() };
let outer = std::mem::replace(&mut self.ctx, inner);
@@ -1085,32 +1160,28 @@ impl<'s> Parser<'s> {
}
/// The parameters an arrow function's parenthesized head `expr` gives (ECMA-262 2015 section
/// 14.2.1): names, names with `= default`, and a last `...name`, each written bare.
fn arrow_params(&self, expr: ExprId) -> Result<Params> {
let invalid = |at: ExprId| self.error_at_offset(self.ast.expr_span(at).start, "invalid arrow function parameters");
let Some(Expr::Paren(inner)) = self.ast.expr(expr) else { return Err(invalid(expr)) };
/// 14.2.1): names or patterns, each with an optional `= default`, and a last `...name` or
/// `...[pattern]`.
fn arrow_params(&mut self, expr: ExprId) -> Result<Params> {
let invalid = |p: &Self, at: ExprId| p.error_at_offset(p.ast.expr_span(at).start, "invalid arrow function parameters");
let Some(Expr::Paren(inner)) = self.ast.expr(expr) else { return Err(invalid(self, expr)) };
let items = match self.ast.expr(*inner) {
Some(Expr::Sequence(list)) => list.clone(),
_ => vec![*inner],
};
let (mut params, mut defaults, mut rest) = (Vec::new(), Vec::new(), None);
let name_of = |id: ExprId| match self.ast.expr(id) {
Some(Expr::Ident(n)) => Some(Name { name: n.clone(), span: self.ast.expr_span(id) }),
_ => None,
};
let count = items.len();
for (i, item) in items.into_iter().enumerate() {
match self.ast.expr(item) {
Some(Expr::Ident(_)) => {
params.push(name_of(item).ok_or_else(|| invalid(item))?);
match self.ast.expr(item).cloned() {
Some(Expr::Assign { op: None, target, value }) => {
params.push(self.arrow_param(target).ok_or_else(|| invalid(self, item))??);
defaults.push(Some(value));
}
Some(Expr::Spread(arg)) if i + 1 == count => rest = Some(self.arrow_param(arg).ok_or_else(|| invalid(self, item))??),
_ => {
params.push(self.arrow_param(item).ok_or_else(|| invalid(self, item))??);
defaults.push(None);
}
Some(Expr::Assign { op: None, target, value }) => {
params.push(name_of(*target).ok_or_else(|| invalid(item))?);
defaults.push(Some(*value));
}
Some(Expr::Spread(arg)) if i + 1 == count => rest = Some(name_of(*arg).ok_or_else(|| invalid(item))?),
_ => return Err(invalid(item)),
}
}
Ok((params, defaults, rest))
@@ -1128,16 +1199,17 @@ impl<'s> Parser<'s> {
}
/// The rules for a function's name and parameters. Strict mode code (Annex C): neither `eval`,
/// `arguments` nor a strict-mode reserved word, and no parameter name twice. An arrow function
/// or a function with a default or rest parameter has no parameter name twice either (ECMA-262
/// 2015 sections 14.1.2 and 14.2.1), and its body cannot start with `"use strict"`
/// (`body_strict`; ECMA-262 2016 section 14.1.2).
/// `arguments` nor a strict-mode reserved word, and no parameter name twice. An arrow function,
/// a method or a function with a default or rest parameter has no parameter name twice either
/// (ECMA-262 2015 sections 14.1.2, 14.2.1 and 14.3.1), and its body cannot start with
/// `"use strict"` (`body_strict`; ECMA-262 2016 section 14.1.2).
fn check_params(&self, function: &Function, body_strict: bool) -> Result<()> {
let params = || function.params.iter().chain(&function.rest);
let simple = function.simple_params() && function.kind != FunctionKind::Arrow;
let names: Vec<Name> = function.params.iter().chain(&function.rest).flat_map(|p| self.ast.bound_names(p)).collect();
let params = || names.iter();
let simple = function.simple_params() && !matches!(function.kind, FunctionKind::Arrow | FunctionKind::Method);
if body_strict && !function.simple_params() {
let at = function.body.first().map_or(function.span.start, |&s| self.ast.stmt_span(s).start);
return Err(self.error_at_offset(at, "\"use strict\" is not allowed in a function with default or rest parameters"));
return Err(self.error_at_offset(at, "\"use strict\" is not allowed in a function with default, rest or destructured parameters"));
}
if function.strict {
for n in function.name.iter().chain(params()) {
@@ -1183,10 +1255,16 @@ impl<'s> Parser<'s> {
}
fn parse_assignment(&mut self, no_in: bool) -> Result<ExprId> {
let cover_ok = std::mem::take(&mut self.cover_ok);
let mark = self.cover_inits.len();
self.enter()?;
let result = self.assignment(no_in);
self.leave();
result
let expr = result?;
if !cover_ok {
self.check_cover(mark)?;
}
Ok(expr)
}
/// `a = b += c`: the targets kept on a stack, so a long chain does not nest.
@@ -1205,7 +1283,11 @@ impl<'s> Parser<'s> {
}
return Ok(value);
};
self.check_target(expr, "invalid assignment target")?;
if op.is_none() && self.es2015 && matches!(self.ast.expr(expr), Some(Expr::Array(_) | Expr::Object(_))) {
self.check_assignment_pattern(expr)?;
} else {
self.check_target(expr, "invalid assignment target")?;
}
self.bump()?;
targets.push((expr, op));
}
@@ -1216,7 +1298,7 @@ impl<'s> Parser<'s> {
fn arrow_from(&mut self, expr: ExprId, no_in: bool) -> Result<ExprId> {
let start = self.ast.expr_span(expr);
let params = match self.ast.expr(expr) {
Some(Expr::Ident(name)) => (vec![Name { name: name.clone(), span: start }], vec![None], None),
Some(Expr::Ident(name)) => (vec![Binding::Name(Name { name: name.clone(), span: start })], vec![None], None),
Some(Expr::Paren(_)) => self.arrow_params(expr)?,
_ => return Err(self.unexpected()),
};
@@ -1562,15 +1644,16 @@ impl<'s> Parser<'s> {
let start = self.expect(Punct::LParen)?.span;
let mut items = Vec::new();
let mut head_only = self.at(Punct::RParen);
let mark = self.cover_inits.len();
while !self.at(Punct::RParen) {
if self.at(Punct::Ellipsis) {
let spread_start = self.bump()?.span;
let name = self.binding_identifier()?;
let arg = self.ast.push_expr(Expr::Ident(name.name), name.span);
let arg = self.binding_target_expr()?;
items.push(self.ast.push_expr(Expr::Spread(arg), self.span_from(spread_start)));
head_only = true;
break;
}
self.cover_ok = true;
items.push(self.parse_assignment(false)?);
if !self.eat(Punct::Comma)? {
break;
@@ -1583,6 +1666,9 @@ impl<'s> Parser<'s> {
if head_only && !self.at(Punct::Arrow) {
return Err(self.error_at_token(&self.tok, format!("expected '=>' but found {}", describe(&self.tok))));
}
if !self.at(Punct::Arrow) {
self.check_cover(mark)?;
}
let inner = match items.as_slice() {
[one] => *one,
_ => {
@@ -1637,29 +1723,61 @@ impl<'s> Parser<'s> {
elements.push(None);
continue;
}
elements.push(Some(self.parse_element()?));
self.cover_ok = self.es2015;
let element = self.parse_element()?;
elements.push(Some(element));
if !self.at(Punct::RBracket) {
self.expect(Punct::Comma)?;
if matches!(self.ast.expr(element), Some(Expr::Spread(_))) {
self.rest_commas.insert(element.0);
}
}
}
Ok(self.ast.push_expr(Expr::Array(elements), self.span_from(start)))
}
/// `{a: 1, "b": 2, 3: c, get d() {…}, set d(v) {…}}`. A name may repeat, a later definition
/// replacing an earlier one (ECMA-262 2015 section 12.2.6.1).
/// replacing an earlier one (ECMA-262 2015 section 12.2.6.1). With [`crate::Options::es2015`],
/// also computed names, shorthand properties and methods ([`Self::parse_property_es2015`]).
fn parse_object(&mut self) -> Result<ExprId> {
let start = self.expect(Punct::LBrace)?.span;
let mut properties = Vec::new();
while !self.eat(Punct::RBrace)? {
let property = self.parse_property()?;
let property = if self.es2015 { self.parse_property_es2015()? } else { self.parse_property()? };
properties.push(property);
if !self.at(Punct::RBrace) {
self.expect(Punct::Comma)?;
}
}
if self.es2015 {
self.note_proto_twice(&properties);
}
Ok(self.ast.push_expr(Expr::Object(properties), self.span_from(start)))
}
/// Records each `__proto__: value` of `properties` after the first in `proto_twice` and, in
/// order, in `cover_inits`.
fn note_proto_twice(&mut self, properties: &[Property]) {
// The offsets rise along the properties, so they are merged into the sorted list in one
// pass.
let twice: Vec<u32> = properties.iter().filter(|p| p.is_proto_setter(&self.ast)).skip(1).map(|p| p.span.start).collect();
let Some(&lowest) = twice.first() else { return };
let first = self.cover_inits.partition_point(|&x| x < lowest);
let tail = self.cover_inits.split_off(first);
let (mut a, mut b) = (tail.into_iter().peekable(), twice.iter().copied().peekable());
while let (Some(&x), Some(&y)) = (a.peek(), b.peek()) {
if y <= x {
self.cover_inits.push(y);
b.next();
} else {
self.cover_inits.push(x);
a.next();
}
}
self.cover_inits.extend(b.chain(a));
self.proto_twice.extend(twice);
}
fn parse_property(&mut self) -> Result<Property> {
let start = self.tok.span;
// `get` and `set` start an accessor only when written without escapes.
+402
View File
@@ -0,0 +1,402 @@
//! `for (… of …)` and destructuring with [`crate::Options::es2015`] (ECMA-262 11th edition,
//! <https://262.ecma-international.org/11.0/>): binding patterns in declarations, parameters and
//! catch clauses (section 13.3.3), assignment patterns read from array and object literals
//! (section 12.15.5), and the shorthand, computed and `name = default` properties an object
//! literal takes while it may still turn out to be a pattern (section 12.2.6).
//!
//! A pattern is kept as the array or object expression it looks like (see [`Binding`]). A binding
//! pattern is read as one; an assignment pattern is read as a literal and checked when an `=` or a
//! loop head shows that it is a pattern.
use super::{Parser, Result, describe, property_key};
use crate::ast::{Binding, Expr, ExprId, ForInTarget, FunctionKind, Name, Property, PropertyKey, PropertyValue, Stmt, StmtId, VarDecl};
use crate::token::{Punct, Span, TokenKind};
impl Parser<'_> {
/// The current token is `of` written without escapes, in a loop head.
pub(super) fn at_of(&self) -> bool {
self.es2015 && self.tok.ident() == Some("of") && !self.tok.escaped
}
/// A shorthand property with an initializer (`{a = 1}`) or a second `__proto__: value` read
/// since `mark` that no pattern took is a `SyntaxError`.
pub(super) fn check_cover(&self, mark: usize) -> Result<()> {
match self.cover_inits.get(mark) {
Some(&at) if self.proto_twice.contains(&at) => Err(self.error_at_offset(at, "an object literal must not set '__proto__' twice")),
Some(&at) => Err(self.error_at_offset(at, "a shorthand property cannot have an initializer outside a destructuring pattern")),
None => Ok(()),
}
}
/// The name or pattern a `var`, `let`, `const` or catch clause declares.
pub(super) fn parse_declaration_target(&mut self) -> Result<Binding> {
if self.es2015 && (self.at(Punct::LBracket) || self.at(Punct::LBrace)) {
return Ok(Binding::Pattern(self.parse_binding_pattern()?));
}
Ok(Binding::Name(self.binding_identifier()?))
}
/// A parameter's name or pattern; a name's strict-mode checks wait for the body.
pub(super) fn parse_param_target(&mut self) -> Result<Binding> {
if self.es2015 && (self.at(Punct::LBracket) || self.at(Punct::LBrace)) {
return Ok(Binding::Pattern(self.parse_binding_pattern()?));
}
Ok(Binding::Name(self.function_name_or_param()?.0))
}
/// `[…]` or `{…}`: a binding pattern, each nested pattern counted as one more level of
/// nesting.
pub(super) fn parse_binding_pattern(&mut self) -> Result<ExprId> {
self.enter()?;
let result = if self.at(Punct::LBracket) { self.binding_array() } else { self.binding_object() };
self.leave();
result
}
/// `[a, , [b], c = 1, ...d]`: a comma with nothing before it skips a value, and a rest element
/// comes last, without a comma after it.
fn binding_array(&mut self) -> Result<ExprId> {
let start = self.expect(Punct::LBracket)?.span;
let mut elements = Vec::new();
loop {
if self.eat(Punct::RBracket)? {
break;
}
if self.eat(Punct::Comma)? {
elements.push(None);
continue;
}
if self.at(Punct::Ellipsis) {
let rest_start = self.bump()?.span;
let target = self.binding_target_expr()?;
elements.push(Some(self.ast.push_expr(Expr::Spread(target), self.span_from(rest_start))));
if !self.at(Punct::RBracket) {
return Err(self.error_at_token(&self.tok, "a rest element must be the last element of a pattern"));
}
continue;
}
elements.push(Some(self.binding_element()?));
if !self.at(Punct::RBracket) {
self.expect(Punct::Comma)?;
}
}
Ok(self.ast.push_expr(Expr::Array(elements), self.span_from(start)))
}
/// `{a, b = 1, c: d, "e": [f], [g]: h = 2}`.
fn binding_object(&mut self) -> Result<ExprId> {
let start = self.expect(Punct::LBrace)?.span;
let mut properties = Vec::new();
while !self.eat(Punct::RBrace)? {
let property_start = self.tok.span;
let shorthand = matches!(self.tok.kind, TokenKind::Ident(_)) && !self.peek().is_some_and(|t| t.is_punct(Punct::Colon));
let (key, value) = if shorthand {
let name = self.binding_identifier()?;
let target = self.ast.push_expr(Expr::Ident(name.name.clone()), name.span);
(PropertyKey::Ident(name.name), self.binding_default(target)?)
} else {
let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 };
self.expect(Punct::Colon)?;
(key, self.binding_element()?)
};
properties.push(Property { key, value: PropertyValue::Init(value), span: self.span_from(property_start) });
if !self.at(Punct::RBrace) {
self.expect(Punct::Comma)?;
}
}
Ok(self.ast.push_expr(Expr::Object(properties), self.span_from(start)))
}
/// A name or a nested pattern, as a pattern's target.
pub(super) fn binding_target_expr(&mut self) -> Result<ExprId> {
if self.es2015 && (self.at(Punct::LBracket) || self.at(Punct::LBrace)) {
return self.parse_binding_pattern();
}
let name = self.binding_identifier()?;
Ok(self.ast.push_expr(Expr::Ident(name.name), name.span))
}
/// A pattern's target with its optional default value.
fn binding_element(&mut self) -> Result<ExprId> {
let target = self.binding_target_expr()?;
self.binding_default(target)
}
/// `= value` after a target, kept as an assignment whose target is the target.
fn binding_default(&mut self, target: ExprId) -> Result<ExprId> {
if !self.eat(Punct::Eq)? {
return Ok(target);
}
let value = self.parse_assignment(false)?;
let span = self.ast.expr_span(target).to(self.ast.expr_span(value));
Ok(self.ast.push_expr(Expr::Assign { op: None, target, value }, span))
}
/// `[expression]` as a property name.
fn computed_key(&mut self) -> Result<PropertyKey> {
self.expect(Punct::LBracket)?;
let key = self.parse_assignment(false)?;
self.expect(Punct::RBracket)?;
Ok(PropertyKey::Computed(key))
}
/// A property of an object literal with [`crate::Options::es2015`]: what ECMAScript 5.1 reads,
/// a computed name (`[k]: v`, `get [k]() {}`), a shorthand name (`a`, the value of `a`), a
/// method (`m() {}`, `[k]() {}`; ECMA-262 2015 section 14.3), and a shorthand name with an
/// initializer (`a = 1`), which only a pattern may hold.
pub(super) fn parse_property_es2015(&mut self) -> Result<Property> {
let start = self.tok.span;
// `get` and `set` start an accessor only when written without escapes and followed by a
// property name.
let accessor = match self.tok.ident().filter(|_| !self.tok.escaped) {
Some("get") => Some(FunctionKind::Getter),
Some("set") => Some(FunctionKind::Setter),
_ => None,
};
if let Some(kind) = accessor
&& self.peek().is_some_and(|t| property_key(&t).is_some() || t.is_punct(Punct::LBracket))
{
self.bump()?;
let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 };
let function = self.parse_function_rest(kind, None, start)?;
let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) };
return Ok(Property { key, value, span: self.span_from(start) });
}
if self.at(Punct::LBracket) {
let key = self.computed_key()?;
return self.cover_property_value(key, start);
}
if let TokenKind::Ident(name) = &self.tok.kind
&& self.peek().is_some_and(|t| t.is_punct(Punct::Comma) || t.is_punct(Punct::RBrace) || t.is_punct(Punct::Eq))
{
let name = name.clone();
self.check_identifier(&self.tok, &name)?;
let token = self.bump()?;
let target = self.ast.push_expr(Expr::Ident(name.clone()), token.span);
let value = if self.at(Punct::Eq) {
self.cover_inits.push(self.tok.span.start);
self.bump()?;
let init = self.parse_assignment(false)?;
let span = token.span.to(self.ast.expr_span(init));
self.ast.push_expr(Expr::Assign { op: None, target, value: init }, span)
} else {
target
};
return Ok(Property { key: PropertyKey::Ident(name), value: PropertyValue::Init(value), span: self.span_from(start) });
}
let (key, _) = self.parse_property_key()?;
self.cover_property_value(key, start)
}
/// A method's parameters and body after its name, or `: value` after a property name, where
/// the value may still turn out to be a pattern.
fn cover_property_value(&mut self, key: PropertyKey, start: Span) -> Result<Property> {
if self.at(Punct::LParen) {
let function = self.parse_function_rest(FunctionKind::Method, None, start)?;
return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) });
}
self.expect(Punct::Colon)?;
self.cover_ok = true;
let value = self.parse_assignment(false)?;
Ok(Property { key, value: PropertyValue::Init(value), span: self.span_from(start) })
}
/// An assignment's, `++`'s or `--`'s target without the call that ECMAScript 5.1 code may
/// assign to: an identifier (in strict code neither `eval` nor `arguments`), a property or an
/// E4X name standing alone.
fn check_simple_target(&self, expr: ExprId, message: &str) -> Result<()> {
let inner = self.ast.unparenthesized(expr);
match self.ast.expr(inner) {
Some(Expr::Ident(name)) => {
if self.ctx.strict && super::is_eval_or_arguments(name) {
return Err(self.error_at_offset(self.ast.expr_span(inner).start, format!("cannot assign to '{name}' in strict mode")));
}
Ok(())
}
Some(Expr::Member { .. } | Expr::Index { .. } | Expr::XmlScopeName(_)) => Ok(()),
_ => Err(self.error_at_offset(self.ast.expr_span(expr).start, message)),
}
}
/// A `for-in` or `for-of` loop's target expression: an assignment pattern, or a target that
/// an assignment takes (without a call in a `for-of` loop).
pub(super) fn loop_target(&mut self, expr: ExprId, message: &str, of: bool) -> Result<()> {
if self.es2015 && matches!(self.ast.expr(expr), Some(Expr::Array(_) | Expr::Object(_))) {
return self.check_assignment_pattern(expr);
}
if of { self.check_simple_target(expr, message) } else { self.check_target(expr, message) }
}
/// The targets of the elements and property values of the pattern `id`, each with its default
/// value taken off. A rest element that is not last or has a comma after it, and a method, a
/// getter or a setter, are errors.
fn pattern_targets(&self, id: ExprId) -> Result<Vec<ExprId>> {
let mut out = Vec::new();
match self.ast.expr(id) {
Some(Expr::Array(elements)) => {
let count = elements.len();
for (i, el) in elements.iter().enumerate() {
let Some(el) = *el else { continue };
if let Some(Expr::Spread(arg)) = self.ast.expr(el) {
if i + 1 != count || self.rest_commas.contains(&el.0) {
return Err(self.error_at_offset(self.ast.expr_span(el).start, "a rest element must be the last element of a pattern"));
}
out.push(*arg);
} else {
out.push(self.without_default(el));
}
}
}
Some(Expr::Object(properties)) => {
for p in properties {
match p.value {
PropertyValue::Init(v) => out.push(self.without_default(v)),
_ => return Err(self.error_at_offset(p.span.start, "a method, getter or setter cannot be a destructuring target")),
}
}
}
_ => return Err(self.error_at_offset(self.ast.expr_span(id).start, "invalid destructuring pattern")),
}
Ok(out)
}
/// An element's target: the target of `target = default`, or the element itself.
fn without_default(&self, el: ExprId) -> ExprId {
match self.ast.expr(el) {
Some(Expr::Assign { op: None, target, .. }) => *target,
_ => el,
}
}
fn is_pattern(&self, id: ExprId) -> bool {
matches!(self.ast.expr(id), Some(Expr::Array(_) | Expr::Object(_)))
}
/// Checks that the array or object literal `pattern` is an assignment pattern (ECMA-262 11th
/// edition, section 12.15.5.1): each target is a nested pattern or one that an assignment
/// takes, a parenthesized pattern is not a target, and the shorthand properties with an
/// initializer in it are no longer errors.
pub(super) fn check_assignment_pattern(&mut self, pattern: ExprId) -> Result<()> {
let mut work = vec![pattern];
let mut gaps = Vec::new();
while let Some(id) = work.pop() {
for target in self.pattern_targets(id)? {
if self.is_pattern(target) {
work.push(target);
} else {
self.check_simple_target(target, "invalid destructuring target")?;
}
}
self.cover_gaps(id, &mut gaps);
}
self.take_covers(pattern, gaps);
Ok(())
}
/// Checks that the array or object literal `pattern`, read as an arrow function's parameter,
/// is a binding pattern: each target is a name written bare or a nested pattern.
fn check_binding_pattern(&mut self, pattern: ExprId) -> Result<()> {
let mut work = vec![pattern];
let mut gaps = Vec::new();
while let Some(id) = work.pop() {
for target in self.pattern_targets(id)? {
match self.ast.expr(target) {
Some(Expr::Ident(_)) => {}
Some(Expr::Array(_) | Expr::Object(_)) => work.push(target),
_ => return Err(self.error_at_offset(self.ast.expr_span(target).start, "invalid arrow function parameters")),
}
}
self.cover_gaps(id, &mut gaps);
}
self.take_covers(pattern, gaps);
Ok(())
}
/// Adds to `gaps` where the `=` of each shorthand property with an initializer that the
/// object pattern `id` holds itself lies: between the property's target and its default value.
/// A pattern may also name `__proto__` more than once, so where each `__proto__: target`
/// starts is added as well.
fn cover_gaps(&self, id: ExprId, gaps: &mut Vec<(u32, u32)>) {
let Some(Expr::Object(properties)) = self.ast.expr(id) else { return };
for p in properties {
if p.is_proto_setter(&self.ast) {
gaps.push((p.span.start, p.span.start.saturating_add(1)));
}
if let PropertyValue::Init(v) = p.value
&& let Some(Expr::Assign { op: None, target, value }) = self.ast.expr(v)
{
gaps.push((self.ast.expr_span(*target).end, self.ast.expr_span(*value).start));
}
}
}
/// Forgets the shorthand properties with an initializer whose `=` lies in one of `gaps`, the
/// gaps of the object patterns in `pattern`. One inside a default value or a computed name
/// stays an error. The positions in `cover_inits` rise, so only those inside `pattern` are
/// read, in one pass with the gaps sorted.
fn take_covers(&mut self, pattern: ExprId, mut gaps: Vec<(u32, u32)>) {
if gaps.is_empty() {
return;
}
gaps.sort_unstable();
let span = self.ast.expr_span(pattern);
let lo = self.cover_inits.partition_point(|&at| at < span.start);
let hi = self.cover_inits.partition_point(|&at| at < span.end).max(lo);
let mut gaps = gaps.into_iter().peekable();
let kept: Vec<u32> = self
.cover_inits
.get(lo..hi)
.unwrap_or_default()
.iter()
.copied()
.filter(|&at| {
while gaps.next_if(|&(_, to)| to <= at).is_some() {}
!gaps.peek().is_some_and(|&(from, to)| from <= at && at < to)
})
.collect();
drop(self.cover_inits.splice(lo..hi, kept));
}
/// An arrow function's parameter from its parenthesized head: `None` when `item` is neither a
/// name nor a pattern.
pub(super) fn arrow_param(&mut self, item: ExprId) -> Option<Result<Binding>> {
match self.ast.expr(item) {
Some(Expr::Ident(name)) => Some(Ok(Binding::Name(Name { name: name.clone(), span: self.ast.expr_span(item) }))),
Some(Expr::Array(_) | Expr::Object(_)) => Some(self.check_binding_pattern(item).map(|()| Binding::Pattern(item))),
_ => None,
}
}
/// `for (var … of …)`, from `of`: the variable takes no initializer, and no catch clause
/// around the loop in the same function has a parameter of the same name (ECMA-262 2015
/// Annex B.3.5).
pub(super) fn parse_for_of_var(&mut self, decl: VarDecl, start: Span) -> Result<StmtId> {
if decl.init.is_some() {
return Err(self.error_at_token(&self.tok, "a for-of variable cannot have an initializer"));
}
for name in self.ast.bound_names(&decl.target) {
for scope in self.scopes.iter().rev() {
if !scope.function && scope.params.contains(&name.name) {
return Err(self.redeclared(&name));
}
if scope.function {
break;
}
}
}
self.parse_for_of(ForInTarget::Var(decl), start)
}
/// The rest of `for (target of iterable) body`, from `of`; the iterable is an assignment
/// expression.
pub(super) fn parse_for_of(&mut self, target: ForInTarget, start: Span) -> Result<StmtId> {
if !self.at_of() {
return Err(self.error_at_token(&self.tok, format!("expected 'of' but found {}", describe(&self.tok))));
}
self.bump()?;
let iterable = self.parse_assignment(false)?;
self.expect(Punct::RParen)?;
let body = self.parse_loop_body()?;
Ok(self.ast.push_stmt(Stmt::ForOf { target, iterable, body }, self.span_from(start)))
}
}
+21 -1
View File
@@ -109,7 +109,9 @@ impl Interrupt {
}
}
/// A value passed between a script and the host. An object is given by its class name.
/// A value passed between a script and the host. An object is given by its class name, and a
/// Symbol by its description; a Symbol the host passes in is a new Symbol each time, and one a
/// host function returns in a realm without [`Options::es2015`] throws a `TypeError`.
#[derive(Clone, Debug, PartialEq)]
pub enum JsValue {
Undefined,
@@ -118,6 +120,7 @@ pub enum JsValue {
Number(f64),
String(String),
Object(String),
Symbol(Option<String>),
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -274,6 +277,23 @@ impl Realm {
interp.finally_marks.clear();
interp.finally_sites.clear();
interp.error_mark = None;
// The first run with ECMAScript 2015 names the built-in functions; a run whose heap has no
// room for the names ends with the heap limit, and the next run tries again.
if interp.options.es2015
&& let Err(e) = crate::builtins::es2015_names(interp)
{
return match self.outcome(Err(e)) {
Err(e) => Err(e),
Ok(_) => Err(RunError {
kind: RunErrorKind::Internal,
message: "the built-in function names could not be set".into(),
line: 0,
column: 0,
authored: false,
}),
};
}
let interp = &mut self.interp;
let strict = interp.options.strict;
interp.evaluated = next_tag(interp.evaluated);
self.script_tag = interp.evaluated;
+2
View File
@@ -209,6 +209,8 @@ pub(crate) fn find(interp: &mut Interp, hay: &[u16], needle: &[u16], from: usize
/// `String(value)` and `new String(value)` (sections 15.5.1 and 15.5.2).
fn string_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult<Value> {
let s = match args.first() {
// `String(symbol)` gives `Symbol(description)` (ECMA-262 11th edition, section 21.1.1.1).
Some(Value::Symbol(sym)) if !construct => return interp.descriptive_string(sym),
Some(v) => interp.to_str(v)?,
None => Str::from(""),
};
+625
View File
@@ -0,0 +1,625 @@
//! Symbols (ECMA-262 11th edition, section 6.1.5, <https://262.ecma-international.org/11.0/>) and
//! the properties they name.
//!
//! A Symbol is a value with its own identity and an optional description; two Symbols are equal
//! only when they are the same Symbol. An object keeps its Symbol-keyed properties apart from its
//! string-keyed ones, in the order they were added, so `for-in`, `Object.keys`,
//! `Object.getOwnPropertyNames` and `JSON` see only names, and `Object.getOwnPropertySymbols` sees
//! only Symbols. `Symbol.for`'s registry belongs to the realm and lives as long as it does; each
//! entry counts against the heap limit. A realm without [`crate::Options::es2015`] makes no Symbol,
//! so its scripts run as before.
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use crate::heap::{ObjId, PROP_BYTES, Prop, WRITABLE};
use crate::interp::{Desc, Hint, Interp, JsResult, merge_desc};
use crate::value::{Str, Value};
/// A Symbol value. Clones share the Symbol; equality and hashing compare identity.
#[derive(Clone)]
pub(crate) struct Sym(Rc<SymData>);
struct SymData {
description: Option<Str>,
/// `Symbol.for` made it, and the registry holds it under its description.
registered: bool,
}
impl Sym {
pub(crate) fn new(description: Option<Str>, registered: bool) -> Self {
Sym(Rc::new(SymData { description, registered }))
}
pub(crate) fn description(&self) -> Option<&Str> {
self.0.description.as_ref()
}
pub(crate) fn registered(&self) -> bool {
self.0.registered
}
/// An address that identifies the Symbol, for counting it once.
pub(crate) fn addr(&self) -> usize {
Rc::as_ptr(&self.0) as *const () as usize
}
/// `Symbol(description)` for a message, with at most [`NAMED_UNITS`] units of the description
/// followed by `...` when it has more, and the work reading them took: the rope nodes visited
/// plus the units read. The description is not flattened or copied whole.
pub(crate) fn message_name(&self) -> (Vec<u16>, u64) {
let mut units: Vec<u16> = "Symbol(".encode_utf16().collect();
let mut work = 0;
if let Some(d) = self.description() {
let (part, visited) = d.prefix(NAMED_UNITS, NAMED_NODES);
work = visited.saturating_add(part.len() as u64);
let cut = part.len() < d.len();
units.extend_from_slice(&part);
if cut {
units.extend("...".encode_utf16());
}
}
units.push(u16::from(b')'));
(units, work)
}
}
/// The most units of a Symbol's description a message names.
const NAMED_UNITS: usize = 256;
/// The most rope nodes read for the units a message names.
const NAMED_NODES: u64 = 4 * NAMED_UNITS as u64;
impl PartialEq for Sym {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
impl Eq for Sym {}
impl Hash for Sym {
fn hash<H: Hasher>(&self, state: &mut H) {
self.addr().hash(state);
}
}
impl std::fmt::Debug for Sym {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", String::from_utf16_lossy(&self.message_name().0))
}
}
/// An object's Symbol-keyed properties in the order they were added. A removed entry leaves a
/// gap until half the entries are gaps, so removing keeps the order without moving the rest.
#[derive(Clone, Default)]
pub(crate) struct SymProps {
entries: Vec<Option<(Sym, Prop)>>,
index: HashMap<Sym, usize>,
}
impl SymProps {
pub(crate) fn get(&self, k: &Sym) -> Option<&Prop> {
let i = *self.index.get(k)?;
self.entries.get(i)?.as_ref().map(|(_, p)| p)
}
pub(crate) fn get_mut(&mut self, k: &Sym) -> Option<&mut Prop> {
let i = *self.index.get(k)?;
self.entries.get_mut(i)?.as_mut().map(|(_, p)| p)
}
/// Sets the property under `k`, keeping its place when it is there already. Returns whether
/// the key is new.
pub(crate) fn insert(&mut self, k: Sym, prop: Prop) -> bool {
if let Some(slot) = self.get_mut(&k) {
*slot = prop;
return false;
}
self.index.insert(k.clone(), self.entries.len());
self.entries.push(Some((k, prop)));
true
}
pub(crate) fn remove(&mut self, k: &Sym) -> Option<Prop> {
let i = self.index.remove(k)?;
let (_, prop) = self.entries.get_mut(i)?.take()?;
if self.entries.len() > 16 && self.index.len() * 2 < self.entries.len() {
self.entries.retain(Option::is_some);
self.entries.shrink_to_fit();
self.index = self.entries.iter().enumerate().filter_map(|(i, e)| e.as_ref().map(|(k, _)| (k.clone(), i))).collect();
}
Some(prop)
}
pub(crate) fn len(&self) -> usize {
self.index.len()
}
pub(crate) fn iter(&self) -> impl Iterator<Item = (&Sym, &Prop)> {
self.entries.iter().filter_map(|e| e.as_ref().map(|(k, p)| (k, p)))
}
}
/// A property key (section 6.1.7): a name or a Symbol.
pub(crate) enum PropKey {
Str(crate::heap::Key),
Sym(Sym),
}
/// The well-known Symbols a realm has (section 6.1.5.1): `Symbol.iterator` and the others the
/// language reads, with `Symbol.asyncIterator`, which nothing reads yet.
pub(crate) struct WellKnown {
pub(crate) iterator: Sym,
pub(crate) async_iterator: Sym,
pub(crate) has_instance: Sym,
pub(crate) to_primitive: Sym,
pub(crate) to_string_tag: Sym,
/// The five as values, for the collector.
values: Vec<Value>,
}
impl WellKnown {
pub(crate) fn new() -> Self {
let make = |name: &str| Sym::new(Some(Str::from(name)), false);
let (iterator, async_iterator, has_instance, to_primitive, to_string_tag) = (
make("Symbol.iterator"),
make("Symbol.asyncIterator"),
make("Symbol.hasInstance"),
make("Symbol.toPrimitive"),
make("Symbol.toStringTag"),
);
let values = [&iterator, &async_iterator, &has_instance, &to_primitive, &to_string_tag].into_iter().cloned().map(Value::Symbol).collect();
WellKnown { iterator, async_iterator, has_instance, to_primitive, to_string_tag, values }
}
}
/// The objects of a realm with [`crate::Options::es2015`] that the interpreter itself uses.
#[derive(Clone, Copy)]
pub(crate) struct Es2015Objects {
pub(crate) symbol_proto: ObjId,
pub(crate) array_iterator_proto: ObjId,
pub(crate) string_iterator_proto: ObjId,
/// `%ArrayProto_values%`, the `@@iterator` of every `arguments` object.
pub(crate) array_values: ObjId,
/// `Function.prototype[@@hasInstance]`.
pub(crate) has_instance: ObjId,
}
/// The estimated bytes of a registry entry without its Symbol.
pub(crate) const REGISTRY_ENTRY_BYTES: usize = 48;
/// A realm's Symbols: the well-known ones, `Symbol.for`'s registry and the built-in objects that
/// go with them. All are `None` or empty in a realm without [`crate::Options::es2015`].
#[derive(Default)]
pub(crate) struct Symbols {
pub(crate) well_known: Option<WellKnown>,
/// Each key `Symbol.for` was given, with its Symbol as a value.
pub(crate) registry: HashMap<Rc<[u16]>, Value>,
pub(crate) objects: Option<Es2015Objects>,
}
impl Symbols {
/// The values the collector starts from.
pub(crate) fn root_values(&self) -> impl Iterator<Item = &Value> {
self.well_known.iter().flat_map(|w| w.values.iter()).chain(self.registry.values())
}
/// The objects the collector starts from.
pub(crate) fn root_objects(&self) -> Vec<ObjId> {
self.objects.map_or_else(Vec::new, |o| vec![o.symbol_proto, o.array_iterator_proto, o.string_iterator_proto, o.array_values, o.has_instance])
}
/// The bytes the registry's entries hold besides their Symbols, which a collection adds.
pub(crate) fn registry_bytes(&self) -> usize {
self.registry.len().saturating_mul(REGISTRY_ENTRY_BYTES)
}
}
impl Interp {
/// ToPropertyKey (section 7.1.14): a Symbol, or an object whose primitive value is one, stays a
/// Symbol; any other value becomes a name.
#[allow(clippy::wrong_self_convention)]
pub(crate) fn to_prop_key(&mut self, v: &Value) -> JsResult<PropKey> {
match v {
Value::Symbol(s) => Ok(PropKey::Sym(s.clone())),
Value::Object(_) => match self.to_primitive(v, Hint::String)? {
Value::Symbol(s) => Ok(PropKey::Sym(s)),
p => self.to_key(&p).map(PropKey::Str),
},
_ => self.to_key(v).map(PropKey::Str),
}
}
/// Runs `f` with the key [`Self::to_prop_key`] makes from `v`, kept reachable while `f` runs
/// when it was converted from another value.
pub(crate) fn with_prop_key<T>(&mut self, v: &Value, f: impl FnOnce(&mut Self, PropKey) -> JsResult<T>) -> JsResult<T> {
match v {
Value::Symbol(s) => f(self, PropKey::Sym(s.clone())),
Value::Object(_) => {
let p = self.to_primitive(v, Hint::String)?;
self.rooted(std::slice::from_ref(&p), |i| match &p {
Value::Symbol(s) => f(i, PropKey::Sym(s.clone())),
_ => i.with_key(&p, |i, k| f(i, PropKey::Str(k))),
})
}
_ => self.with_key(v, |i, k| f(i, PropKey::Str(k))),
}
}
/// [`Sym::message_name`] as code units, its reading charged as fuel.
pub(crate) fn sym_name_units(&mut self, k: &Sym) -> JsResult<Vec<u16>> {
let (units, work) = k.message_name();
crate::regexp_vm::use_fuel_n(self, work.max(1))?;
Ok(units)
}
/// [`Sym::message_name`] as text, its reading charged as fuel.
pub(crate) fn sym_name(&mut self, k: &Sym) -> JsResult<String> {
self.sym_name_units(k).map(|u| String::from_utf16_lossy(&u))
}
/// `prefix`, the units of `body` and `suffix` as a new string. Flattening `body` and building
/// the string are charged as fuel and checked against the heap limit first.
pub(crate) fn wrap_str(&mut self, prefix: &str, body: Option<&Str>, suffix: &str) -> JsResult<Value> {
let body = match body {
Some(b) => crate::string_builtins::flat_charged(self, b)?,
None => Rc::from([]),
};
let (prefix, suffix): (Vec<u16>, Vec<u16>) = (prefix.encode_utf16().collect(), suffix.encode_utf16().collect());
let len = prefix.len().saturating_add(body.len()).saturating_add(suffix.len());
crate::string_builtins::reserve_units(self, len)?;
let mut units = Vec::with_capacity(len);
units.extend_from_slice(&prefix);
units.extend_from_slice(&body);
units.extend_from_slice(&suffix);
Ok(Value::String(Str::from_units(units)))
}
/// SymbolDescriptiveString (section 19.4.3.3.1): `Symbol(description)` as a new string.
pub(crate) fn descriptive_string(&mut self, k: &Sym) -> JsResult<Value> {
let roots = [Value::Symbol(k.clone())];
self.rooted(&roots, |i| i.wrap_str("Symbol(", k.description(), ")"))
}
/// A `TypeError` for a property `k` that cannot be defined, when `throw`; otherwise `false`.
fn reject_sym_bool(&mut self, throw: bool, k: &Sym, why: &str) -> JsResult<bool> {
if !throw {
return Ok(false);
}
let name = self.sym_name_units(k)?;
self.reject_bool(true, &name, why)
}
/// A `TypeError` for a property `k` that cannot be set, when `throw`.
fn reject_sym(&mut self, throw: bool, k: &Sym, why: &str) -> JsResult<()> {
if !throw {
return Ok(());
}
let name = self.sym_name_units(k)?;
self.reject(true, &name, why)
}
pub(crate) fn get_own_sym(&self, id: ObjId, k: &Sym) -> JsResult<Option<Prop>> {
Ok(self.object(id)?.syms.as_ref().and_then(|m| m.get(k)).cloned())
}
/// The property `k` found on the object or its prototype chain. Each step to a prototype takes
/// a unit of fuel.
pub(crate) fn find_sym(&mut self, id: ObjId, k: &Sym) -> JsResult<Option<Prop>> {
let mut cur = Some(id);
let mut steps = 0usize;
while let Some(o) = cur {
if let Some(p) = self.get_own_sym(o, k)? {
return Ok(Some(p));
}
cur = self.object(o)?.proto;
if cur.is_some() {
self.use_fuel()?;
}
steps += 1;
if steps > 1_000_000 {
return Err(crate::interp::Abrupt::Internal("prototype chain too long".into()));
}
}
Ok(None)
}
/// [[Get]] of `k` starting at `start`, with `receiver` as `this` for a getter.
pub(crate) fn get_sym_from(&mut self, start: ObjId, k: &Sym, receiver: &Value) -> JsResult<Value> {
match self.find_sym(start, k)? {
None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined),
Some(Prop::Data { value, .. }) => Ok(value),
Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]),
}
}
/// `base[k]` for any value.
pub(crate) fn get_value_sym(&mut self, base: &Value, k: &Sym) -> JsResult<Value> {
if base.is_nullish() {
let (key, base) = (self.sym_name(k)?, if matches!(base, Value::Null) { "null" } else { "undefined" });
return Err(self.type_error(&format!("cannot read property '{key}' of {base}")));
}
let start = self.primitive_proto(base, &[])?;
self.get_sym_from(start, k, base)
}
/// Adds or replaces an own property directly, keeping the heap estimate.
pub(crate) fn define_sym(&mut self, id: ObjId, k: Sym, prop: Prop) -> JsResult<()> {
let o = self.object_mut(id)?;
if o.syms.get_or_insert_with(Box::default).insert(k, prop) {
self.heap.bytes = self.heap.bytes.saturating_add(PROP_BYTES);
}
Ok(())
}
/// The default [[DefineOwnProperty]] (section 9.1.6) for a Symbol key.
pub(crate) fn define_own_sym(&mut self, id: ObjId, k: Sym, desc: &Desc, throw: bool) -> JsResult<bool> {
let Some(current) = self.get_own_sym(id, &k)? else {
if !self.object(id)?.extensible {
return self.reject_sym_bool(throw, &k, "the object is not extensible");
}
let mut roots = vec![Value::Object(id), Value::Symbol(k.clone())];
roots.extend(desc.value.iter().cloned());
roots.extend(desc.get.flatten().into_iter().chain(desc.set.flatten()).map(Value::Object));
self.rooted(&roots, |i| i.reserve_heap(PROP_BYTES))?;
let flags = desc.flags_or(0);
let prop = if desc.is_accessor() {
Prop::Accessor { get: desc.get.flatten(), set: desc.set.flatten(), flags: flags & !WRITABLE }
} else {
Prop::Data { value: desc.value.clone().unwrap_or(Value::Undefined), flags }
};
self.define_sym(id, k, prop)?;
return Ok(true);
};
let Some(merged) = merge_desc(&current, desc) else { return self.reject_sym_bool(throw, &k, "the property cannot be redefined") };
self.define_sym(id, k, merged)?;
Ok(true)
}
/// [[Set]] (section 9.1.9) of an ordinary object for a Symbol key.
pub(crate) fn put_sym(&mut self, id: ObjId, k: Sym, v: Value, throw: bool) -> JsResult<()> {
match self.get_own_sym(id, &k)? {
Some(Prop::Data { flags, .. }) => {
if flags & WRITABLE == 0 {
return self.reject_sym(throw, &k, "it is read-only");
}
if let Some(Some(Prop::Data { value, .. })) = self.object_mut(id)?.syms.as_mut().map(|m| m.get_mut(&k)) {
*value = v;
}
return Ok(());
}
Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop),
Some(Prop::Accessor { set: None, .. }) => return self.reject_sym(throw, &k, "it has only a getter"),
None => {}
}
let proto = self.object(id)?.proto;
match proto.map(|p| self.find_sym(p, &k)).transpose()?.flatten() {
Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop),
Some(Prop::Accessor { set: None, .. }) => return self.reject_sym(throw, &k, "it has only a getter"),
Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject_sym(throw, &k, "it is read-only"),
_ => {}
}
if !self.object(id)?.extensible {
return self.reject_sym(throw, &k, "the object is not extensible");
}
let roots = [Value::Object(id), Value::Symbol(k.clone()), v.clone()];
self.rooted(&roots, |i| i.reserve_heap(PROP_BYTES))?;
self.define_sym(id, k, Prop::Data { value: v, flags: crate::heap::OPEN })
}
/// PutValue (section 6.2.4.9) on a Symbol-keyed reference, whose base may be a primitive.
pub(crate) fn put_value_sym(&mut self, base: &Value, k: Sym, v: Value) -> JsResult<()> {
match base {
Value::Object(o) => {
let throw = self.strict_writes();
self.put_sym(*o, k, v, throw)
}
Value::Undefined | Value::Null => {
let (key, base) = (self.sym_name(&k)?, if matches!(base, Value::Null) { "null" } else { "undefined" });
Err(self.type_error(&format!("cannot set property '{key}' of {base}")))
}
_ => {
let proto = self.primitive_proto(base, &[])?;
if let Some(Prop::Accessor { set: Some(s), .. }) = self.find_sym(proto, &k)? {
return self.call(&Value::Object(s), base, &[v]).map(drop);
}
let strict = self.strict();
self.reject_sym(strict, &k, "the value is a primitive")
}
}
}
/// [[Delete]] (section 9.1.10) for a Symbol key.
pub(crate) fn delete_sym(&mut self, id: ObjId, k: &Sym, throw: bool) -> JsResult<bool> {
match self.get_own_sym(id, k)? {
None => Ok(true),
Some(p) if p.configurable() => {
if let Some(m) = self.object_mut(id)?.syms.as_mut() {
m.remove(k);
}
Ok(true)
}
Some(_) if throw => {
let key = self.sym_name(k)?;
Err(self.type_error(&format!("cannot delete property '{key}'")))
}
Some(_) => Ok(false),
}
}
/// An object's own Symbol keys in the order they were added. Each takes a unit of fuel, and
/// the heap for the list is checked first.
pub(crate) fn own_symbols(&mut self, id: ObjId) -> JsResult<Vec<Sym>> {
let count = self.object(id)?.syms.as_ref().map_or(0, |m| m.len());
self.reserve_heap(count.saturating_mul(16))?;
for _ in 0..count {
self.use_fuel()?;
}
Ok(self.object(id)?.syms.iter().flat_map(|m| m.iter()).map(|(k, _)| k.clone()).collect())
}
// ---- either kind of key ----
pub(crate) fn get_own_pk(&self, id: ObjId, k: &PropKey) -> JsResult<Option<Prop>> {
match k {
PropKey::Str(name) => self.get_own_property(id, name),
PropKey::Sym(s) => self.get_own_sym(id, s),
}
}
pub(crate) fn has_pk(&mut self, id: ObjId, k: &PropKey) -> JsResult<bool> {
match k {
PropKey::Str(name) => self.has_property(id, name),
PropKey::Sym(s) => Ok(self.find_sym(id, s)?.is_some()),
}
}
pub(crate) fn define_own_pk(&mut self, id: ObjId, k: PropKey, desc: &Desc, throw: bool) -> JsResult<bool> {
match k {
PropKey::Str(name) => self.define_own_property(id, name, desc, throw),
PropKey::Sym(s) => self.define_own_sym(id, s, desc, throw),
}
}
pub(crate) fn get_value_pk(&mut self, base: &Value, k: &PropKey) -> JsResult<Value> {
match k {
PropKey::Str(name) => self.get_value(base, name),
PropKey::Sym(s) => self.get_value_sym(base, s),
}
}
pub(crate) fn put_value_pk(&mut self, base: &Value, k: PropKey, v: Value) -> JsResult<()> {
match k {
PropKey::Str(name) => self.put_value(base, name, v),
PropKey::Sym(s) => self.put_value_sym(base, s, v),
}
}
pub(crate) fn delete_pk(&mut self, id: ObjId, k: &PropKey, throw: bool) -> JsResult<bool> {
match k {
PropKey::Str(name) => self.delete(id, name, throw),
PropKey::Sym(s) => self.delete_sym(id, s, throw),
}
}
// ---- the hooks the well-known Symbols name ----
/// The well-known Symbol `pick` chooses, in a realm that has them.
pub(crate) fn well_known(&self, pick: fn(&WellKnown) -> &Sym) -> Option<Sym> {
self.symbols.well_known.as_ref().map(|w| pick(w).clone())
}
/// Steps 2 and 3 of ToPrimitive (section 7.1.1): the result of the object's
/// `@@toPrimitive` method called with the hint, or `None` when it has none. Code run without
/// [`crate::Options::es2015`] reads no such method, even in a realm that has the well-known
/// Symbols from an earlier run.
pub(crate) fn exotic_to_primitive(&mut self, o: ObjId, v: &Value, hint: Hint) -> JsResult<Option<Value>> {
if !self.options.es2015 {
return Ok(None);
}
let Some(sym) = self.well_known(|w| &w.to_primitive) else { return Ok(None) };
let f = self.get_sym_from(o, &sym, v)?;
if f.is_nullish() {
return Ok(None);
}
if !self.is_callable(&f) {
return Err(self.type_error("the value is not a function"));
}
let hint = match hint {
Hint::Default => "default",
Hint::Number => "number",
Hint::String => "string",
};
let r = self.call(&f, v, &[Value::str(hint)])?;
if matches!(r, Value::Object(_)) {
return Err(self.type_error("cannot convert the object to a primitive value"));
}
Ok(Some(r))
}
/// Steps 2 to 4 of InstanceofOperator (section 12.10.4): the answer of `f`'s
/// `@@hasInstance` method, or `None` when `f` is not an object or has none. Code run without
/// [`crate::Options::es2015`] reads no such method, so `instanceof` keeps the ECMAScript 5.1
/// check that the right side is a function.
pub(crate) fn has_instance_hook(&mut self, v: &Value, f: &Value) -> JsResult<Option<bool>> {
if !self.options.es2015 {
return Ok(None);
}
let Some(sym) = self.well_known(|w| &w.has_instance) else { return Ok(None) };
let Value::Object(fid) = f else { return Ok(None) };
let handler = self.get_sym_from(*fid, &sym, f)?;
if handler.is_nullish() {
return Ok(None);
}
if !self.is_callable(&handler) {
return Err(self.type_error("the value is not a function"));
}
Ok(Some(self.call(&handler, f, std::slice::from_ref(v))?.truthy()))
}
/// For the target of a bound function in OrdinaryHasInstance (section 7.3.21, step 2): the
/// answer of its own `@@hasInstance` method when that is not `Function.prototype`'s, whose
/// answer is the one the caller goes on to give.
pub(crate) fn bound_target_hook(&mut self, v: &Value, target: ObjId) -> JsResult<Option<bool>> {
let default = self.symbols.objects.map(|o| o.has_instance);
match self.has_instance_handler(target)? {
Some(h) if Some(h) != default => {
let f = Value::Object(target);
Ok(Some(self.call(&Value::Object(h), &f, std::slice::from_ref(v))?.truthy()))
}
_ => Ok(None),
}
}
/// `target[@@hasInstance]` when it is callable, `None` when it is absent or the code runs
/// without [`crate::Options::es2015`]; anything else throws a `TypeError`.
fn has_instance_handler(&mut self, target: ObjId) -> JsResult<Option<ObjId>> {
if !self.options.es2015 {
return Ok(None);
}
let Some(sym) = self.well_known(|w| &w.has_instance) else { return Ok(None) };
let handler = self.get_sym_from(target, &sym, &Value::Object(target))?;
match handler {
Value::Undefined | Value::Null => Ok(None),
Value::Object(h) if self.is_callable(&handler) => Ok(Some(h)),
_ => Err(self.type_error("the value is not a function")),
}
}
/// The `@@toStringTag` of `o` when it is a string (section 19.1.3.6, steps 15 and 16). Code
/// run without [`crate::Options::es2015`] reads no tag, so it gets the ECMAScript 5.1 result
/// even in a realm that has the well-known Symbols from an earlier run.
pub(crate) fn string_tag_of(&mut self, o: ObjId) -> JsResult<Option<Str>> {
if !self.options.es2015 {
return Ok(None);
}
let Some(sym) = self.well_known(|w| &w.to_string_tag) else { return Ok(None) };
match self.get_sym_from(o, &sym, &Value::Object(o))? {
Value::String(s) => Ok(Some(s)),
_ => Ok(None),
}
}
}
#[cfg(test)]
mod tests {
use super::{Sym, SymProps};
use crate::heap::{OPEN, Prop};
use crate::value::Value;
#[test]
fn removing_most_symbol_keys_gives_back_their_room_and_keeps_the_order() {
let mut m = SymProps::default();
let keys: Vec<Sym> = (0..100).map(|_| Sym::new(None, false)).collect();
for k in &keys {
m.insert(k.clone(), Prop::Data { value: Value::Undefined, flags: OPEN });
}
for k in &keys[..90] {
m.remove(k);
}
assert!(m.entries.capacity() < 64, "{}", m.entries.capacity());
assert_eq!(m.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>(), keys[90..]);
}
}
+437
View File
@@ -0,0 +1,437 @@
//! `Symbol`, Symbol-keyed properties and the iterators of arrays, strings and `arguments`
//! objects, in a realm with [`Options::es2015`].
use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind};
fn es2015(limits: Limits) -> Realm {
Realm::with_options(Options { es2015: true, ..Options::default() }, limits)
}
fn run(src: &str) -> JsValue {
match es2015(Limits::default()).run(src) {
Ok(v) => v,
Err(e) => panic!("{src}\n{e:?}"),
}
}
fn truth(src: &str) {
assert_eq!(run(src), JsValue::Bool(true), "{src}");
}
fn string(src: &str) -> String {
match run(src) {
JsValue::String(s) => s,
other => panic!("{src}: {other:?}"),
}
}
/// The run throws an error whose message starts with `name`.
fn throws(src: &str, name: &str) {
match es2015(Limits::default()).run(src) {
Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"),
other => panic!("{src}: {other:?}"),
}
}
#[test]
fn symbols_are_unique_values_with_a_description() {
truth("typeof Symbol() === 'symbol' && typeof Symbol('a') === 'symbol'");
truth("Symbol('a') !== Symbol('a') && Symbol('a') != Symbol('a')");
truth("var s = Symbol('a'); s === s && s == Object(s) && Object(s) == s");
truth("Symbol('a').description === 'a' && Symbol().description === undefined && Symbol('').description === ''");
assert_eq!(string("String(Symbol('a b'))"), "Symbol(a b)");
assert_eq!(string("Symbol().toString()"), "Symbol()");
truth("var s = Symbol(); Object(s).valueOf() === s && typeof Object(s) === 'object'");
truth("Object.prototype.toString.call(Symbol()) === '[object Symbol]'");
truth("!!Symbol() && Symbol.length === 0 && Symbol.prototype.constructor === Symbol");
throws("new Symbol()", "TypeError");
throws("Symbol.prototype.toString.call({})", "TypeError");
}
#[test]
fn symbol_for_and_key_for_use_the_registry() {
truth("Symbol.for('k') === Symbol.for('k') && Symbol.for('k') !== Symbol('k')");
truth("Symbol.keyFor(Symbol.for('k')) === 'k' && Symbol.keyFor(Symbol('k')) === undefined");
truth("Symbol.keyFor(Symbol.iterator) === undefined && Symbol.for('x').description === 'x'");
throws("Symbol.keyFor('k')", "TypeError");
throws("Symbol.for(Symbol())", "TypeError");
}
#[test]
fn implicit_conversion_of_a_symbol_throws_a_type_error() {
throws("Symbol() + ''", "TypeError");
throws("'' + Symbol('a')", "TypeError");
throws("+Symbol()", "TypeError");
throws("Symbol() * 2", "TypeError");
throws("Symbol() < 1", "TypeError");
throws("[Symbol()].join()", "TypeError");
throws("'abc'.indexOf(Symbol())", "TypeError");
throws("Symbol(Symbol())", "TypeError");
throws("new String(Symbol())", "TypeError");
truth("String(Symbol('x')) === 'Symbol(x)' && Symbol('x').toString() === 'Symbol(x)'");
}
#[test]
fn symbol_keys_are_hidden_from_for_in_keys_and_json() {
let setup = "var s = Symbol('s'); var o = {a: 1}; o[s] = 2; ";
truth(&format!("{setup} var n = []; for (var k in o) n.push(k); n.join() === 'a'"));
truth(&format!("{setup} Object.keys(o).join() === 'a' && Object.getOwnPropertyNames(o).join() === 'a'"));
truth(&format!("{setup} JSON.stringify(o) === '{{\"a\":1}}'"));
truth("JSON.stringify({a: Symbol()}) === '{}' && JSON.stringify([Symbol()]) === '[null]' && JSON.stringify(Symbol()) === undefined");
truth(&format!("{setup} var l = Object.getOwnPropertySymbols(o); l.length === 1 && l[0] === s && o[s] === 2"));
truth(&format!("{setup} s in o && o.hasOwnProperty(s) && o.propertyIsEnumerable(s) && delete o[s] && !(s in o)"));
truth(&format!("{setup} o[Object(s)] === 2 && o[s.toString()] === undefined"));
throws("var w = new String('x'); w.toString = function () { return Symbol(); }; JSON.stringify(w)", "TypeError");
truth("var o = Object(Symbol()); delete Symbol.prototype[Symbol.toStringTag]; Object.prototype.toString.call(o) === '[object Object]'");
}
#[test]
fn define_property_freeze_and_descriptors_take_symbol_keys() {
truth(
"var s = Symbol(); var o = {}; Object.defineProperty(o, s, {value: 1}); \
var d = Object.getOwnPropertyDescriptor(o, s); d.value === 1 && !d.writable && !d.enumerable && !d.configurable",
);
truth("var s = Symbol(); var o = {}; o[s] = 1; Object.freeze(o); o[s] = 2; o[s] === 1 && Object.isFrozen(o)");
truth("var s = Symbol(); var o = {}; o[s] = 1; Object.preventExtensions(o); Object.isSealed(o) === false");
truth("var s = Symbol(); var p = {}; p[s] = {value: 3, enumerable: true}; var o = Object.create(null, p); o[s] === 3");
throws("'use strict'; var s = Symbol(); var o = Object.freeze((function () { var x = {}; x[s] = 1; return x; })()); o[s] = 2;", "TypeError");
truth("var s = Symbol(); var o = {}; o[s] = 1; o[s]++; o[s] === 2");
}
#[test]
fn code_run_without_the_option_reads_no_to_string_tag() {
let mut realm = es2015(Limits::default());
let setup = "var read = 0, o = {}; Object.defineProperty(o, Symbol.toStringTag, { get: function () { read++; return 'Thing'; } }); \
Object.prototype.toString.call(o) === '[object Thing]' && read === 1";
assert_eq!(realm.run(setup), Ok(JsValue::Bool(true)));
realm.set_es2015(false);
assert_eq!(realm.run("Object.prototype.toString.call(o) === '[object Object]' && read === 1"), Ok(JsValue::Bool(true)));
}
#[test]
fn code_run_without_the_option_calls_no_to_primitive_or_has_instance_method() {
let mut realm = es2015(Limits::default());
let setup = "var o = { valueOf: function () { return 1; } }; o[Symbol.toPrimitive] = function () { return 2; }; \
var c = {}; c[Symbol.hasInstance] = function () { return true; }; \
function F() {} var B = F.bind(); \
Object.defineProperty(F, Symbol.hasInstance, { value: function () { return true; } }); \
o + 1 === 3 && ({} instanceof c) && ({} instanceof B)";
assert_eq!(realm.run(setup), Ok(JsValue::Bool(true)));
realm.set_es2015(false);
assert_eq!(realm.run("o + 1 === 2 && !({} instanceof B)"), Ok(JsValue::Bool(true)));
match realm.run("({} instanceof c)") {
Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("TypeError"), "{message}"),
other => panic!("{other:?}"),
}
}
#[test]
fn well_known_symbols_hook_the_operations_that_read_them() {
truth("var o = {}; o[Symbol.toStringTag] = 'Thing'; Object.prototype.toString.call(o) === '[object Thing]'");
truth("var o = {}; o[Symbol.toPrimitive] = function (h) { return h === 'number' ? 7 : 'str'; }; +o === 7 && String(o) === 'str'");
throws("var o = {}; o[Symbol.toPrimitive] = function () { return {}; }; +o", "TypeError");
throws("var o = {}; o[Symbol.toPrimitive] = 1; +o", "TypeError");
truth("var C = {}; C[Symbol.hasInstance] = function (v) { return v === 1; }; (1 instanceof C) && !(2 instanceof C)");
truth("function F() {} var B = F.bind(); new F() instanceof B && typeof Function.prototype[Symbol.hasInstance] === 'function'");
truth("Function.prototype[Symbol.hasInstance].call(Array, []) === true && Function.prototype[Symbol.hasInstance].call({}, []) === false");
truth(
"Symbol.iterator.toString() === 'Symbol(Symbol.iterator)' && typeof Symbol.asyncIterator === 'symbol' \
&& typeof Symbol.hasInstance === 'symbol' && typeof Symbol.toPrimitive === 'symbol' && typeof Symbol.toStringTag === 'symbol'",
);
}
#[test]
fn an_array_iterator_driven_by_hand_steps_through_values_keys_and_entries() {
truth(
"var it = [10, 20][Symbol.iterator](); var a = it.next(), b = it.next(), c = it.next(), d = it.next(); \
a.value === 10 && !a.done && b.value === 20 && !b.done && c.value === undefined && c.done && d.done",
);
truth("var it = ['a', 'b'].keys(); it.next().value === 0 && it.next().value === 1 && it.next().done");
truth("var e = ['x'].entries().next().value; e.length === 2 && e[0] === 0 && e[1] === 'x'");
truth("Array.prototype[Symbol.iterator] === Array.prototype.values");
truth("var a = [1]; var it = a.values(); it.next(); a.push(2); it.next().value === 2");
truth("var it = [].values(); it[Symbol.iterator]() === it && Object.prototype.toString.call(it) === '[object Array Iterator]'");
truth("var it = Array.prototype.values.call({length: 1, 0: 'q'}); it.next().value === 'q'");
throws("[].values().next.call({})", "TypeError");
throws("[].values().next.call(''[Symbol.iterator]())", "TypeError");
}
#[test]
fn a_string_iterator_steps_by_code_point() {
truth(
"var it = 'a\\uD83D\\uDE00b'[Symbol.iterator](); var x = it.next().value, y = it.next().value, z = it.next().value; \
x === 'a' && y === '\\uD83D\\uDE00' && y.length === 2 && z === 'b' && it.next().done",
);
truth("var it = '\\uDE00\\uD83D'[Symbol.iterator](); it.next().value === '\\uDE00' && it.next().value === '\\uD83D' && it.next().done");
truth("Object.prototype.toString.call(''[Symbol.iterator]()) === '[object String Iterator]'");
throws("String.prototype[Symbol.iterator].call(null)", "TypeError");
}
#[test]
fn arguments_objects_have_the_array_values_iterator() {
truth("(function () { return arguments[Symbol.iterator] === Array.prototype.values; })()");
truth("(function () { 'use strict'; var it = arguments[Symbol.iterator](); return it.next().value === 5 && it.next().done; })(5)");
truth("(function () { return !arguments.propertyIsEnumerable(Symbol.iterator); })()");
}
#[test]
fn realms_without_es2015_have_no_symbol() {
for options in [Options::default(), Options { e4x: true, preprocessor_lines: true, ..Options::default() }] {
let mut realm = Realm::with_options(options, Limits::default());
let src = "typeof Symbol === 'undefined' && Array.prototype.values === undefined && Object.getOwnPropertySymbols === undefined";
assert_eq!(realm.run(src), Ok(JsValue::Bool(true)));
let src = "Object.getOwnPropertyNames((function () { return arguments; })()).join()";
assert_eq!(realm.run(src), Ok(JsValue::String("length,callee".into())));
}
}
#[test]
fn symbols_and_the_registry_count_against_the_heap_limit() {
let limits = || Limits { heap_bytes: 1 << 20, fuel: 50_000_000, ..Limits::default() };
let mut realm = es2015(limits());
match realm.run("for (var i = 0; ; i++) Symbol.for('key' + i);") {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {}
other => panic!("{other:?}"),
}
let mut realm = es2015(limits());
match realm.run("var keep = []; for (var i = 0; ; i++) keep.push(Symbol('d' + i));") {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {}
other => panic!("{other:?}"),
}
// Symbols nothing holds are collected, so making them one after another does not fill the
// heap, and keys survive a collection.
let mut realm = es2015(limits());
let src = "var s = Symbol('k'); var o = {}; o[s] = 'v'; for (var i = 0; i < 40000; i++) Symbol('x' + i); o[s] === 'v'";
assert_eq!(realm.run(src), Ok(JsValue::Bool(true)));
}
#[test]
fn an_error_names_a_long_symbol_by_the_start_of_its_description() {
// `d` is a rope of 4,194,304 units whose halves share one node, so it takes little heap until
// something copies it whole. Each error names the Symbol by the first 256 units only.
let setup = "var d = 'x'; for (var i = 0; i < 22; i++) d = d + d; var s = Symbol(d); \
var shut = Object.preventExtensions({}); var fixed = Object.defineProperty({}, s, { value: 1 }); ";
let named = format!("Symbol({}...)", "x".repeat(256));
for (attempt, message) in [
("shut[s] = 1", format!("cannot assign to property '{named}': the object is not extensible")),
("Object.defineProperty(shut, s, { value: 1 })", format!("cannot define property '{named}': the object is not extensible")),
("Object.defineProperty(fixed, s, { value: 2 })", format!("cannot define property '{named}': the property cannot be redefined")),
("fixed[s] = 2", format!("cannot assign to property '{named}': it is read-only")),
("delete fixed[s]", format!("cannot delete property '{named}'")),
("null[s]", "cannot read a property of null".to_string()),
] {
let src = format!(
"{setup} (function () {{ 'use strict'; try {{ {attempt}; return 'none'; }} catch (e) {{ return (e instanceof TypeError) + ' ' + e.message; }} }})()"
);
let mut realm = es2015(Limits { heap_bytes: 64 << 20, fuel: 1_000_000, ..Limits::default() });
assert_eq!(realm.run(&src), Ok(JsValue::String(format!("true {message}"))), "{attempt}");
}
// A write that does not throw leaves the Symbol's description as it is.
let src = format!("{setup} shut[s] = 1; fixed[s] = 2; shut[s] === undefined && fixed[s] === 1");
assert_eq!(es2015(Limits { heap_bytes: 64 << 20, fuel: 1_000_000, ..Limits::default() }).run(&src), Ok(JsValue::Bool(true)));
}
#[test]
fn an_array_iterator_keeps_its_object_while_reading_its_length_runs_script() {
// The `length` getter finishes the iterator by stepping it again, which lets go of `obj`, and
// the length's `valueOf` drops the last reference to `obj`, fills the heap until it collects
// and then reuses every free slot. The step still reads the element of `obj`.
let src = "var obj = { 0: 'x', 1: 'y' }, it = Array.prototype.values.call(obj), calls = 0, junk, fresh = []; \
Object.defineProperty(obj, 'length', { get: function () { \
calls++; if (calls > 1) return 0; it.next(); \
return { valueOf: function () { obj = null; \
for (var i = 0; i < 60000; i++) junk = { a: i }; \
for (var j = 0; j < 70000; j++) fresh.push({ 0: 'wrong' }); return 2; } }; } }); 0; \
var r = it.next(); r.value + ' ' + r.done + ' ' + it.next().done";
assert_eq!(string(src), "x false true");
}
#[test]
fn binary_and_octal_strings_are_numbers_in_an_es2015_realm_only() {
for length in ["0b10", "0o2", "2"] {
let src = format!(
"var it = Array.prototype.values.call({{0: 'first', 1: 'second', length: '{length}'}}); \
var a = it.next(), b = it.next(); a.value + ' ' + b.value + ' ' + it.next().done"
);
assert_eq!(string(&src), "first second true", "{length}");
}
truth("Number('0b101') === 5 && +'0O17' === 15 && '0b11' == 3 && isNaN('0b2') && isNaN('-0o1')");
let src = "isNaN(Number('0b10')) && isNaN(+'0o2') && '0b1' != 1";
assert_eq!(Realm::with_options(Options::default(), Limits::default()).run(src), Ok(JsValue::Bool(true)));
}
#[test]
fn json_calls_the_to_primitive_method_of_a_wrapper() {
let hook = "w[Symbol.toPrimitive] = function (hint) { return hint === 'number' ? 2 : 'b'; };";
truth(&format!("var w = new String('x'); {hook} JSON.stringify(w) === '\"b\"'"));
truth(&format!("var w = new String('x'); delete String.prototype.toString; {hook} JSON.stringify(w) === '\"b\"'"));
truth(&format!("var w = new String('x'); {hook} JSON.stringify({{a: 1, b: 2}}, [w]) === '{{\"b\":2}}'"));
truth(&format!("var w = new Number(5); {hook} JSON.stringify([w], null, w) === '[\\n 2\\n]'"));
truth("JSON.stringify([new String('x'), new Number(1)], null, new Number(1)) === '[\\n \"x\",\\n 1\\n]'");
// A `@@toPrimitive` getter that deletes the prototype's method and gives `undefined` sends the
// lookup on to `Object.prototype`.
let getter = |method: &str| {
format!(
"Object.defineProperty(w, Symbol.toPrimitive, {{ get: function () {{ delete Object.getPrototypeOf(w).{method}; return undefined; }} }});"
)
};
let over = "Object.prototype.toString = function () { return '7'; };";
truth(&format!("var w = new String('x'); {over} {} JSON.stringify(w) === '\"7\"'", getter("toString")));
truth(&format!("var w = new Number(3); {over} delete Number.prototype.toString; {} JSON.stringify(w) === '7'", getter("valueOf")));
}
#[test]
fn a_symbol_key_from_to_primitive_counts_against_the_heap_while_the_property_is_used() {
// `mk(n)` makes a string of `n` units. The key's accessor deletes itself from
// `Object.prototype`, so when the key is a Symbol only the read or write holds it and its
// description of 2,000,000 units, and then makes a string of 1,500,000 units. With `keep`
// (1,000,000 units) and a description still counted, that string does not fit; without one it
// does.
let src = |key: &str, access: &str| {
format!(
"function mk(n) {{ return new Array(n + 1).join('x'); }} \
var keep = mk(1000000), made = null; \
function use() {{ var p = Object.prototype; delete p[Object.getOwnPropertySymbols(p)[0] || 'k']; \
made = mk(1500000); return 0; }} \
var w = {{}}; w[Symbol.toPrimitive] = function () {{ var k = {key}; \
Object.defineProperty(Object.prototype, k, {{ configurable: true, get: use, set: use }}); return k; }}; \
{access}; made.length"
)
};
let limits = || Limits { heap_bytes: 8 << 20, fuel: 50_000_000, ..Limits::default() };
for access in ["({})[w]", "({})[w] = 1", "({})[w]++"] {
// A name as the key leaves the Symbol and its description to the collector, and the string
// fits.
assert_eq!(es2015(limits()).run(&src("(Symbol(mk(2000000)), 'k')", access)), Ok(JsValue::Number(1_500_000.0)), "{access}");
match es2015(limits()).run(&src("Symbol(mk(2000000))", access)) {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {}
other => panic!("{access}: {other:?}"),
}
}
}
#[test]
fn define_properties_keeps_a_symbol_key_counted_after_a_getter_deletes_it() {
// The second Symbol-keyed descriptor's getter deletes the first property, drops `s` and makes
// a string of 1,500,000 units. With `keep` (1,000,000 units) and the first Symbol's
// description of 2,000,000 units still counted, that string does not fit; with a short
// description it does.
let src = |description: &str, define: &str| {
format!(
"function mk(n) {{ return new Array(n + 1).join('x'); }} \
var keep = mk(1000000), made = null, s = Symbol({description}), props = {{}}; \
props[s] = {{ value: 1, enumerable: true }}; \
Object.defineProperty(props, Symbol('t'), {{ enumerable: true, get: function () {{ \
delete props[s]; s = null; made = mk(1500000); return {{ value: 2 }}; }} }}); \
var o = {define}; o[Object.getOwnPropertySymbols(o)[0]] + ' ' + made.length"
)
};
let limits = || Limits { heap_bytes: 8 << 20, fuel: 50_000_000, ..Limits::default() };
for define in ["Object.defineProperties({}, props)", "Object.create(null, props)"] {
assert_eq!(es2015(limits()).run(&src("'d'", define)), Ok(JsValue::String("1 1500000".into())), "{define}");
match es2015(limits()).run(&src("mk(2000000)", define)) {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {}
other => panic!("{define}: {other:?}"),
}
}
}
#[test]
fn an_operator_keeps_the_first_operand_converted_while_it_converts_the_second() {
// `a` converts to a Symbol with a description of 2,000,000 units that nothing else holds, and
// `b`'s conversion makes a string of 1,500,000 units. With `keep` (1,000,000 units) and the
// description still counted, that string does not fit; when `a` gives a number it does.
let src = |first: &str, op: &str| {
format!(
"function mk(n) {{ return new Array(n + 1).join('x'); }} \
var keep = mk(1000000), made = null; \
var a = {{}}; a[Symbol.toPrimitive] = function () {{ return {first}; }}; \
var b = {{}}; b[Symbol.toPrimitive] = function () {{ made = mk(1500000); return 1; }}; \
try {{ a {op} b; }} catch (e) {{ if (!(e instanceof TypeError)) throw e; }} \
made.length === 1500000"
)
};
let limits = || Limits { heap_bytes: 8 << 20, fuel: 50_000_000, ..Limits::default() };
for op in ["+", "<", ">", "<=", ">="] {
assert_eq!(es2015(limits()).run(&src("(Symbol(mk(2000000)), 0)", op)), Ok(JsValue::Bool(true)), "{op}");
match es2015(limits()).run(&src("Symbol(mk(2000000))", op)) {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {}
other => panic!("{op}: {other:?}"),
}
}
}
#[test]
fn date_objects_convert_through_their_to_primitive_method() {
let date = "var d = new Date(0); d.valueOf = function () { return 7; }; d.toString = function () { return 'date'; };";
truth(&format!("{date} d + 1 === 'date1' && d * 1 === 7 && String(d) === 'date' && (d == 'date')"));
// Without a method, a Date converts with `valueOf` first when no hint is given.
// The inherited method is read-only, so an assignment does not shadow it.
truth(&format!("{date} d[Symbol.toPrimitive] = null; d + 1 === 'date1'"));
truth(&format!("{date} Object.defineProperty(d, Symbol.toPrimitive, {{ value: null }}); d + 1 === 8"));
truth(&format!("{date} Object.defineProperty(d, Symbol.toPrimitive, {{ value: undefined }}); d + 1 === 8 && String(d) === 'date'"));
truth(&format!("{date} delete Date.prototype[Symbol.toPrimitive]; d + 1 === 8 && d == 7"));
// The method itself, on any object.
truth(
"var m = Date.prototype[Symbol.toPrimitive], p = Object.getOwnPropertyDescriptor(Date.prototype, Symbol.toPrimitive); \
typeof m === 'function' && m.length === 1 && !p.writable && !p.enumerable && p.configurable",
);
let o = "var o = { valueOf: function () { return 7; }, toString: function () { return 's'; } }, m = Date.prototype[Symbol.toPrimitive];";
truth(&format!("{o} m.call(o, 'number') === 7 && m.call(o, 'string') === 's' && m.call(o, 'default') === 's'"));
for call in ["m.call(o)", "m.call(o, 'other')", "m.call(o, new String('number'))", "m.call(1, 'number')", "m.call(o, 'defaultx')"] {
throws(&format!("{o} {call}"), "TypeError");
}
// A realm without the option keeps the String-hint order for a Date.
let src = format!("{date} d + 1 === 'date1' && d * 1 === 7");
assert_eq!(Realm::with_options(Options::default(), Limits::default()).run(&src), Ok(JsValue::Bool(true)));
}
#[test]
fn a_host_function_returns_a_symbol_only_in_an_es2015_realm() {
let symbol = |_: &[JsValue]| -> Result<JsValue, String> { Ok(JsValue::Symbol(Some("from host".into()))) };
let mut realm = es2015(Limits::default());
realm.define_function("make", symbol);
assert_eq!(realm.run("var s = make(); typeof s === 'symbol' && String(s) === 'Symbol(from host)' && s !== make()"), Ok(JsValue::Bool(true)));
let mut realm = Realm::with_options(Options::default(), Limits::default());
realm.define_function("make", symbol);
let src = "try { make(); 'none'; } catch (e) { (e instanceof TypeError) + ' ' + typeof Symbol; }";
assert_eq!(realm.run(src), Ok(JsValue::String("true undefined".into())));
}
#[test]
fn a_host_symbol_description_counts_against_the_heap_before_it_is_made() {
let mut realm = es2015(Limits { heap_bytes: 1 << 20, ..Limits::default() });
realm.define_function("make", |_| Ok(JsValue::Symbol(Some("d".repeat(1 << 20)))));
match realm.run("make()") {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {}
other => panic!("{other:?}"),
}
let mut realm = es2015(Limits { heap_bytes: 1 << 20, ..Limits::default() });
realm.define_function("make", |_| Ok(JsValue::Symbol(Some("d".repeat(1_000)))));
assert_eq!(realm.run("make().description.length"), Ok(JsValue::Number(1_000.0)));
}
#[test]
fn a_symbol_lookup_takes_fuel_for_each_prototype() {
// Building the chain takes about 20,000 units; each lookup of an absent Symbol walks all 2,000
// prototypes, so the 100 lookups take 200,000 more.
let src = "var s = Symbol(), o = {}; for (var i = 0; i < 2000; i++) o = Object.create(o); \
for (var j = 0; j < 100; j++) s in o;";
match es2015(Limits { fuel: 150_000, ..Limits::default() }).run(src) {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {}
other => panic!("{other:?}"),
}
let src = "var s = Symbol(), root = {}, o = root; root[s] = 'found'; for (var i = 0; i < 50; i++) o = Object.create(o); \
o[s] === 'found' && s in o && !o.hasOwnProperty(s)";
truth(src);
}
#[test]
fn iterator_steps_take_fuel() {
let mut realm = es2015(Limits { fuel: 5_000, ..Limits::default() });
let src = "var a = []; a.length = 1e9; var it = a.values(); while (!it.next().done) {}";
match realm.run(src) {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {}
other => panic!("{other:?}"),
}
}
+14 -6
View File
@@ -1,10 +1,18 @@
use proptest::prelude::*;
use crate::{
BinaryOp, Expr, ExprId, ForInTarget, FunctionKind, Options, Program, PropertyValue, Stmt, StmtId, SyntaxError, TOO_DEEP, TokenKind, parse,
tokenize,
BinaryOp, Binding, Expr, ExprId, ForInTarget, FunctionKind, Options, Program, PropertyValue, Stmt, StmtId, SyntaxError, TOO_DEEP, TokenKind,
VarDecl, parse, tokenize,
};
/// The name a declaration binds; a pattern fails the test.
fn decl_name(d: &VarDecl) -> &str {
match &d.target {
Binding::Name(n) => &n.name,
Binding::Pattern(_) => panic!("a pattern where a name was expected"),
}
}
fn ok(src: &str) -> Program {
match parse(src, &Options::default()) {
Ok(p) => p,
@@ -382,7 +390,7 @@ fn string_literals_and_escapes() {
fn identifiers_with_unicode_and_escapes() {
let p = ok("var caf\\u00e9 = 1, \u{3b1}\u{3b2} = 2, $_x1 = 3, a\u{300} = 4;");
let Stmt::Var(decls) = stmt(&p, p.body[0]) else { panic!() };
let names: Vec<&str> = decls.iter().map(|d| d.name.name.as_str()).collect();
let names: Vec<&str> = decls.iter().map(decl_name).collect();
assert_eq!(names, ["caf\u{e9}", "\u{3b1}\u{3b2}", "$_x1", "a\u{300}"]);
let p = ok("\\u{61}b;");
assert!(matches!(expr(&p, first_expr(&p)), Expr::Ident(n) if n == "ab"));
@@ -427,7 +435,7 @@ fn identifiers_take_the_other_id_start_and_continue_characters() {
for src in [format!("var {ch} = 1;"), format!("var a{ch} = 1;"), format!("var \\u{c:04X}\\u{{{c:X}}} = 1;")] {
let p = ok(&src);
let Stmt::Var(decls) = stmt(&p, p.body[0]) else { panic!("{src:?}") };
assert!(decls[0].name.name.contains(ch), "{src:?}");
assert!(decl_name(&decls[0]).contains(ch), "{src:?}");
}
}
// Other_ID_Continue: may follow the first character, but cannot start a name.
@@ -456,7 +464,7 @@ fn identifiers_take_the_characters_unicode_17_assigned() {
] {
let p = ok(src);
let Stmt::Var(decls) = stmt(&p, p.body[0]) else { panic!("{src:?}") };
assert_eq!(decls[0].name.name, name, "{src:?}");
assert_eq!(decl_name(&decls[0]), name, "{src:?}");
}
assert!(err("var \u{1ACF} = 1;").message.contains("unexpected character"));
assert!(err("var \\u1ACF = 1;").message.contains("identifier escape"));
@@ -480,7 +488,7 @@ fn identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes() {
// A supplementary letter is one identifier character, at the start and after a number.
let p = ok("var \u{10000}\u{1D7CE} = 1;");
let Stmt::Var(decls) = stmt(&p, p.body[0]) else { panic!() };
assert_eq!(decls[0].name.name, "\u{10000}\u{1D7CE}");
assert_eq!(decl_name(&decls[0]), "\u{10000}\u{1D7CE}");
assert!(err("1\u{10000};").message.contains("immediately after numeric literal"));
}
+1 -1
View File
@@ -303,7 +303,7 @@ fn parse_text(units: &[u16]) -> Option<(f64, Unit)> {
}
}
let (number, rest) = text.split_at_checked(k)?;
let value = string_to_number(number);
let value = string_to_number(number, false);
let u = rest.iter().position(|&u| !is_str_space(u)).unwrap_or(rest.len());
let unit = Unit::named(rest.get(u..)?)?;
value.is_finite().then_some((value, unit))
+58 -8
View File
@@ -19,6 +19,9 @@ pub(crate) enum Value {
Number(f64),
String(Str),
Object(ObjId),
/// A Symbol (ECMA-262 11th edition, section 6.1.5), which only a realm with
/// [`crate::Options::es2015`] makes.
Symbol(crate::symbol::Sym),
}
impl Value {
@@ -44,7 +47,7 @@ impl Value {
Value::Bool(b) => *b,
Value::Number(n) => !(n.is_nan() || *n == 0.0),
Value::String(s) => s.len() > 0,
Value::Object(_) => true,
Value::Object(_) | Value::Symbol(_) => true,
}
}
}
@@ -191,6 +194,30 @@ impl Str {
}
}
/// At most `max` code units from the start, read along the rope without flattening it,
/// visiting at most `max_nodes` nodes, with the number of nodes visited. When the nodes run
/// out first, the units read so far are returned.
pub(crate) fn prefix(&self, max: usize, max_nodes: u64) -> (Vec<u16>, u64) {
let mut units = Vec::new();
let mut stack = vec![self.clone()];
let mut visited = 0u64;
while let Some(node) = stack.pop() {
if units.len() >= max || visited >= max_nodes {
break;
}
visited += 1;
match &*node.0.borrow() {
Node::Flat(f) => units.extend_from_slice(f.get(..f.len().min(max - units.len())).unwrap_or_default()),
Node::Concat { left, right, .. } => {
stack.push(right.clone());
stack.push(left.clone());
}
Node::Taken => {}
}
}
(units, visited)
}
pub(crate) fn to_rust_string(&self) -> String {
String::from_utf16_lossy(&self.flat())
}
@@ -236,9 +263,10 @@ pub(crate) fn is_str_space(u: u16) -> bool {
crate::chars::is_whitespace(u32::from(u)) || crate::chars::is_line_terminator(u32::from(u))
}
/// ToNumber applied to a string (section 9.3.1): the StringNumericLiteral grammar, NaN for
/// anything else.
pub(crate) fn string_to_number(units: &[u16]) -> f64 {
/// ToNumber applied to a string (section 9.3.1): the StringNumericLiteral grammar, with the `0b`
/// and `0o` literals of ECMA-262 11th edition, section 7.1.3.1, as well when `binary_octal` is
/// set; NaN for anything else.
pub(crate) fn string_to_number(units: &[u16], binary_octal: bool) -> f64 {
let start = units.iter().position(|&u| !is_str_space(u)).unwrap_or(units.len());
let end = units.iter().rposition(|&u| !is_str_space(u)).map_or(start, |i| i + 1);
let Some(text) = units.get(start..end) else { return f64::NAN };
@@ -252,6 +280,15 @@ pub(crate) fn string_to_number(units: &[u16]) -> f64 {
}
return crate::chars::radix_value(hex.bytes().filter_map(|b| crate::chars::hex_value(u32::from(b))), 16).unwrap_or(f64::NAN);
}
if binary_octal {
for (prefix, radix) in [("0b", 2), ("0B", 2), ("0o", 8), ("0O", 8)] {
let Some(digits) = s.strip_prefix(prefix) else { continue };
if digits.is_empty() || !digits.chars().all(|c| c.is_digit(radix)) {
return f64::NAN;
}
return crate::chars::radix_value(digits.chars().filter_map(|c| c.to_digit(radix)), radix).unwrap_or(f64::NAN);
}
}
let (sign, body) = match s.as_bytes().first() {
Some(b'+') => (1.0, &s[1..]),
Some(b'-') => (-1.0, &s[1..]),
@@ -359,19 +396,32 @@ mod tests {
("-Infinity", f64::NEG_INFINITY),
];
for (s, want) in cases {
assert_eq!(string_to_number(&u(s)), *want, "{s:?}");
assert_eq!(string_to_number(&u(s), false), *want, "{s:?}");
}
for s in ["inf", "nan", "1_0", "0x", "1e", ".", "--1", "0x-1", "infinity", "1 2"] {
assert!(string_to_number(&u(s)).is_nan(), "{s:?}");
assert!(string_to_number(&u(s), false).is_nan(), "{s:?}");
}
}
#[test]
fn binary_and_octal_strings_convert_only_when_asked() {
for (s, want) in [("0b10", 2.0), ("0B11", 3.0), (" 0o17 ", 15.0), ("0O7", 7.0), ("0x10", 16.0), ("2", 2.0)] {
assert_eq!(string_to_number(&u(s), true), want, "{s:?}");
}
for s in ["0b", "0b2", "0o8", "-0b1", "+0o1", "0b1.0", "0o"] {
assert!(string_to_number(&u(s), true).is_nan(), "{s:?}");
}
for s in ["0b10", "0o2"] {
assert!(string_to_number(&u(s), false).is_nan(), "{s:?}");
}
}
#[test]
fn hex_strings_round_once_to_the_nearest_number() {
assert_eq!(string_to_number(&u("0xc83ce80553ee648")), 0xc83_ce80_553e_e648_u64 as f64);
assert_eq!(string_to_number(&u("0xc83ce80553ee648"), false), 0xc83_ce80_553e_e648_u64 as f64);
// 2^136 + 2^83 + 1: a set bit past 128 bits rounds the half-way case up.
let digits = format!("0x1{}8{}1", "0".repeat(13), "0".repeat(19));
assert_eq!(string_to_number(&u(&digits)), 2f64.powi(136) + 2f64.powi(84));
assert_eq!(string_to_number(&u(&digits), false), 2f64.powi(136) + 2f64.powi(84));
}
#[test]
Loaded 100 of 259 files, more files were not shown because too many files have changed in this diff. Show more